2013-08-30 96 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。