问题
I'm trying to populate a 3d array from data stored in an Excel worksheet. I'm hoping I just don't know the syntax, but it may not be possible to 'batch' assign values to 3D arrays like you can with 2D arrays. Such as...
Dim 2DArray() As Variant
2DArray = Range(A1:C10)
This is so clean and efficient I was hoping for something equivalent, as opposed to using 3 nested for-next loops to populate the data one value at a time.
For background this is to lookup/interpolate a gas compressibility factor Z, which is dependent on specific gravity, pressure and temperature. I have 6 tables (really just named ranges) for 6 different values of specific gravity. Each table has pressure and temperature cross-tabulated with Z factor as the datapoint. Here is the code I have (which doesn't work):
Sub Array3DTest()
Dim ZTables() As Variant
ReDim ZTables(1 to 6, 1 to 15, 1 to 9)
'6 specific gravity tables, '15 pressure indices, 9 temp indices
'Here is my feeble attempt to guess the syntax...
'ZTables = ("tblZFactorSG1", "tblZFactorSG2", "tblZFactorSG3",
' "tblZFactorSG4", "tblZFactorSG5", "tblZFactorSG6")
End Sub
To clarify, tblZFactorSG1...SG2...SG3...etc are the 6 named ranges with the cross-tabbed Z factors. All are 15 rows (pressure) by 9 columns (temperature). The last line is commented out because VBA doesn't like the syntax, but maybe you can see what I'm trying to do here. I'm trying to assign the data to the 3Darray in chunks of 15x9. tblZFactorSG1 contains the values that should go in ZTables(1, 1 to 15, 1 to 9). tblZFactorSG2 contains the values that should go in ZTables(2, 1 to 15, 1 to 9).
Thanks in advance for any help.
回答1:
Sub ArrayOfArrays()
Dim ZTables(1 to 6) As Variant, x as Long, ranges
ranges = Array("tblZFactorSG1", "tblZFactorSG2", "tblZFactorSG3", _
"tblZFactorSG4", "tblZFactorSG5", "tblZFactorSG6")
For x=1 to 6
ZTables(x) = ActiveSheet.Range(ranges(x-1)).Value
Next x
End Sub
来源:https://stackoverflow.com/questions/23880740/excel-vba-how-to-populate-a-multi-dimensional-3d-array-with-values-from-multip