在 Excel VBA 中,有没有办法将一个数组存储在另一个数组中?例如,如果我创建了一个名为“World”的 1 维数组和具有各种名称的 2 维数组,是否可以将每个 2D 数组存储到“World”的每个项目中(无论数组“World”有多长)? 如果是这样,我怎么能这样做,我将如何引用“世界”中二维数组中的项目?
我应该考虑使用对象和/或类吗?你是怎么做到的,或者你有什么好地方可以参考我?我在网上找了一段时间,还没有找到解决办法。任何帮助是极大的赞赏。
在我看来,我会使用一个集合。然后,您可以拥有集合的集合。集合很好,因为您可以引用“密钥”并获取相应的值...
Public Function MultiDimensionalCollection() as Collection
Dim tempColl as Collection
Set MultiDimensionalCollection = new Collection
For i = 1 to 100
Set tempColl = New Collection
tempColl.Add "Value", "Key-" & i
tempColl.Add "Value2", "Key2-" & i
tempColl.Add "Value3", "Key3-" & i
MultiDimensionalCollection.Add tempColl, "Key-" & i
Next i
End Function
您显然可以用任何东西(对象、范围值等)填充它们。只要确保你没有重复“KEY”值,否则你会得到一个错误。如果您想要从范围或记录集或您想要的任何内容中填充它们的示例代码,请告诉我。谢谢,布赖恩。
您可能可以为此使用 3d 数组,或者所谓的锯齿状数组(或数组数组)
Sub ThreeDArray()
Dim World() As String ' or type of your choice
ReDim World(0 To 4, 1 To 3, 1 To 2)
World(5, 1, 2) = "a"
Debug.Print World(5, 1, 2)
End Sub
Sub JaggedArray()
Dim World() As Variant
Dim MyArray() As String ' or type of your choice
Dim i As Long, j As Long
' If all elements of World are the same size
ReDim World(0 To 9)
ReDim MyArray(1 To 2, 1 To 3)
For i = LBound(World) To UBound(World)
World(i) = MyArray
Next
' Or, if each element of World is different size
ReDim World(0 To 9)
For i = LBound(World) To UBound(World)
ReDim MyArray(0 To i, 0 To (i + 1) * 2)
World(i) = MyArray
Next
' to access elements
World(5)(1, 2) = "a"
Debug.Print World(5)(1, 2)
End Sub