gpt4 book ai didi

arrays - VBA中的元组列表?

转载 作者:行者123 更新时间:2023-12-01 08:51:54 26 4
gpt4 key购买 nike

我正在尝试在 VBA 中基本上做到这一点:

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

(使用 Python 语法)

所以数组/列表的每个元素都有三个元素。这可以在 VBA 中完成吗?

最佳答案

要扩展数组,请使用 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

当然,由于您添加的项目也是一个数组,因此您可以根据 cyboashu 的回答对单个数组项使用 ReDim Preserve ,但这可能有点乏味/多余.

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

Locals 窗口中 .ToArray 输出的屏幕截图:

enter image description here

关于arrays - VBA中的元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39278335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com