Arrays 如何创建可循环的已分配但长度为零的数组?
我想创建一个VBA数组,该数组包含零个元素,但可用于循环。Arrays 如何创建可循环的已分配但长度为零的数组?,arrays,excel,vba,Arrays,Excel,Vba,我想创建一个VBA数组,该数组包含零个元素,但可用于循环。 您可以查看下面的代码以了解我的意思: Sub testloopemptyarr() Dim spl() As String, v As Variant, count As Integer spl = Split(Empty, ",") 'lbound=0, ubound=-1, zero elements 'ReDim spl(-1 To -1) ' one element '
您可以查看下面的代码以了解我的意思:
Sub testloopemptyarr()
Dim spl() As String, v As Variant, count As Integer
spl = Split(Empty, ",") 'lbound=0, ubound=-1, zero elements
'ReDim spl(-1 To -1) ' one element
'ReDim spl(-1) ' does not compile: subscript out of range
'ReDim spl(-1 To 0) ' two elements
'ReDim spl(0 To -1) ' does not compile: subscript out of range
For Each v In spl
count = count + 1
Next
MsgBox count
End Sub
在这种情况下,msgbox将弹出0,因为拆分空字符串将返回零元素数组。遇到for循环时不会引发错误,这意味着该数组是已分配的数组
如果您测试它,您会发现,在调用Split()之后,lbound(spl)是0,ubound(spl)是-1
但是执行ReDim spl(0到-1)
是非法的(请尝试取消对该行的注释并运行)
所以我的问题是:
如何创建与Split()函数生成的数组具有相同行为的数组
我很想知道您是否可以分配一个空数组。虽然我认为除了使用
Split
检索数组的方式之外,这是不可能的(数组的全部要点是数组中至少有1个元素)
您可能对数组的替代品感兴趣,因为您可以使用ArrayList
对象ArrayList
将允许您仍然像分配的数组一样,为每个索引号向“数组”添加一个项
Sub EmptyArray()
Dim arr As Object: Set arr = CreateObject("System.Collections.ArrayList")
Dim item As Variant
Debug.Print arr.Count 'Will show 0
For Each item In arr 'Will skip iteration
Debug.Print item
Next item
arr.Insert 0, "1st item"
arr.Insert 1, "2nd item"
arr.Insert 2, "3rd item"
Debug.Print arr.Count 'Will show 3
For Each item In arr 'Will now iterate
Debug.Print item
Next item
End Sub
您可以测试vba程序,循环尚未启动,表明阵列已启动empty@jvdvOP完全正确。如果你单步执行他们的代码,并在手表中查看
spl
,你会看到它是暗淡的0到-1
@jvdv如果你注释掉Split()行,数组将是未分配的,for循环行将产生“for loop not initialized”错误92“我想知道你是否可以分配一个空数组。”如果数组消耗内存、具有有效的上下限并包含数据(即使该数据是数组数据类型的默认值,例如字符串类型变量数组的空字符串),则称为已分配数组。根据定义,静态数组总是分配的。“@im_chc,根据您的外观,ArrayList
或Collection
之间的推荐可以。我个人喜欢ArrayList
。我很高兴为您排序=)好吧,这是某些内置函数的异常行为。如果不使用其中一个函数,就无法复制它。这是在CPearsom上讨论的