2013-08-30 163 views
1

在Excel VBA中,有没有办法将数组存储在另一个数组中?例如,如果我创建了一个名为“World”的一维数组和具有各种名称的二维数组,那么是否可以将每个2D数组存储到“World”的每个项目中(但是,数组“World”可能长)?如果是这样,我怎么能做到这一点,我将如何参考“世界”内的二维数组中的项目?将数组存储在数组中

我应该看看使用对象和/或类吗?你如何做到这一点,或者你有一个很好的地方可以参考我?我一直在网上查找一段时间,还没有找到解决方案。任何帮助是极大的赞赏。

+0

如果你在VBA中,那么你想使用'Collection'或'Scripting.Dictionary'来做这样的事情。谷歌他们,有数以千计的例子和帮助网站。 – RBarryYoung

+1

http://stackoverflow.com/questions/4326481/creating-an-array-of-arrays-of-data-objects –

回答

0

您可能能够使用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 
1

在我看来知我会用一个集合。然后您可以拥有集合。集合是好事,因为你可以referece的“钥匙”,并得到相应的价值...

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”值,否则你会得到一个错误。让我知道如果你想要范例或记录集或任何你想要的样例代码。谢谢,Brian。