2016-09-01 88 views
2

我想基本上做的這相當於在VBA:VBA中的元組列表?

myArray.apend((field1, field2, field3)) 

(使用Python語法)

所以一些地方讓陣列/列表中的每個元素有三個要素。這可以在VBA中完成嗎?

+1

你可以有數組內的數組,如果是你是什​​麼意思。類似於'myArray = Array(Array(field1,field2,field3),Array(...),...)' –

+0

我想要動態添加它們的能力,而不僅僅是靜態地全部在一行中 –

回答

6

要擴展陣列,使用ReDim聲明:

Sub foo() 
'## Declares your array of len==1 
ReDim myArray(0) 
myArray(0) = Array("A","B","C") 
'## Extends your array: 
ReDim Preserve myArray(Ubound(myArray)+1) 
myArray(Ubound(myArray)) = Array("item1", "item2", "item3") 

End Sub 

當然,因爲你已經添加的項目也是一個數組,你可以在個別數組項上使用ReDim Preserve,就像per cyboashu的答案一樣,但這可能有點繁瑣/多餘。

Dim chld 
i = UBound(myArray) 
'Get a handle on the child array 
chld = myArray(i) 
'Extend it using ReDim Preserve 
ReDim Preserve chld(UBound(chld) + 1) 
'Add another value to the new item: 
chld(UBound(chld)) = "another value" 
'Reassign back to the parent array 
myArray(i) = chld 

你也使用System.Collections.ArrayList對象:

Sub f() 

Dim myArrayList As Object 
Dim i As Long 

Set myArrayList = ArrayList 

'Add ArrayList child objects to the ArrayList object: 
myArrayList.Add ArrayList 
i = myArrayList.Count - 1 
'Add items to the child ArrayList: 
myArrayList.Item(i).Add "A" 
myArrayList.Item(i).Add "B" 
myArrayList.Item(i).Add "C" 

'Add some more: 
myArrayList.Add ArrayList 
i = myArrayList.Count - 1 
myArrayList.Item(i).Add 1 
myArrayList.Item(i).Add 2 
myArrayList.Item(i).Add 3 

'Dump this in to a VBA Array, if needed: 
Dim myArray 
myArray = myArrayList.ToArray() 

End Sub 
Function ArrayList() 
    Set ArrayList = CreateObject("System.Collections.ArrayList") 
End Function 

在本地窗口的.ToArray輸出的屏幕截圖:

enter image description here

+0

++ great回答。 – cyboashu

1

交錯數組:

例子:

Sub jaggedArray() 


    Dim arrMaster() 
    Dim arrChild() 

    Dim lCtr  As Long 
    Dim lCtr2  As Long 

    For lCtr = 1 To 5 
     ReDim Preserve arrMaster(1 To lCtr) 
     For lCtr2 = 1 To 3 
      ReDim Preserve arrChild(1 To lCtr2) 

      arrChild(lCtr2) = "Child " & lCtr2 

      '/ Assing array in to array 
      arrMaster(lCtr) = arrChild 

     Next 
    Next 


End Sub