代码运行 Ifs 和 Selects,然后将数据添加到单独函数中的数组中。
我还想根据循环数据确定数据发送到哪个数组,并使用变量来存储数组名称,将其传递给实际存储数据的函数。
类似这样的伪代码:
Public Arr1(), Arr2(), Arr3(), Arr4()
Sub ProcessData()
Dim WhichArray, Dim1, Dim2, Dim3 'Also tried WhichArray as Variant
For Each datum in Data
'Ifs and Selects, etc to determine what array the data belongs to and to Redim each array to accommodate.
'e.g. datum belongs in Arr3(3, 1, 2)
WhichArray = Arr3 ' Also tried Set WhichArray = Arr3 here too.
Dim1 = 3
Dim2 = 1
Dim3 = 2
Call fnAddToArray(WhichArray, 3, 1, 2, datum) 'I've tried "ByRef WhichArray As Variant" here too
Next datum
End Sub
然后我想给子打电话:
Sub fnAddToArray(VarArray, Dim1, Dim2, Dim3, Datum)
VarArray(Dim1,Dim2,Dim3) = Datum
End Sub
因为数据太多并且可以进入这 4 个数组中的任何一个,所以我希望能够将数组名称作为变量传递给 Sub,但这只是生成一个名为 VarArray 的新数组并将其存储在那里使用存储在变量中的 Arr3。我还尝试了一个锯齿状数组来存储数组,然后只需将索引传递给子并将值存储在内部数组中,就像我在其他地方看到的那样:
Public DataArrays()
DataArrays = Array(Arr1, Arr2, Arr3, Arr4)
...'same For loop as before, datum belongs in Arr3(3, 1, 2)
WhichArray = 2 '(0 base array)
Dim1 = 3
Dim2 = 1
Dim3 = 2
Call fnAddToArray(WhichArray, Dim1, Dim2, Dim3)
Next datum
End Sub
与子:
Sub fnAddToArray(ArrInd, Dim1, Dim2, Dim3, Datum)
DataArrays(ArrInd)(Dim1, Dim2, Dim3) = Datum
End Sub
这只会在运行时返回类型不匹配错误,甚至声明为变体。我想做的事情可能吗? 如果是这样,我在这里做错了什么?
Option Explicit
Public DataArrays(1 To 4)
Sub tester()
Dim i As Long
InitArrays 'populate the global array
fnAddToArray 2, 1, 3, 44 'update a couple of arrays stored in DataArrays
fnAddToArray 4, 1, 5, 99
'dump the updated arrays back to the sheet
For i = 1 To 4
ActiveSheet.Cells(i, 7).Resize(1, 5).Value = DataArrays(i)
Next i
End Sub
'Populate `DataArrays` with 2D arrays read from a worksheet
Sub InitArrays()
Dim i As Long
For i = 1 To 4
DataArrays(i) = ActiveSheet.Cells(i, 1).Resize(1, 5).Value
Next i
End Sub
Sub fnAddToArray(ArrInd As Long, Dim1 As Long, Dim2 As Long, Datum)
DataArrays(ArrInd)(Dim1, Dim2) = Datum
End Sub
工作表上的值之前/之后: