我想创建一个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
'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 To -1)
(尝试取消注释并运行)是非法的
所以我的问题是:
如何创建与Split()函数产生的数组具有相同行为的数组?
答案 0 :(得分:2)
我很想知道您是否可以分配一个空数组。除了使用Split
检索数组的方式外,尽管我认为不可能(数组的整个IMO是在其中包含元素,至少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