【问题标题】:How to create an allocated but zero-length array that are for-loopable?如何创建可循环的已分配但长度为零的数组?
【发布时间】:2019-10-20 08:59:11
【问题描述】:

我想创建一个包含零个元素但可循环的 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() 函数产生的数组具有相同行为的数组?

【问题讨论】:

  • AFAIK 这是某些内置函数的异常行为。如果不使用这些功能之一,您将无法复制它。这在 CPearsom here 上进行了讨论

标签: arrays excel vba


【解决方案1】:

我很想知道您是否可以分配一个空数组。虽然我认为除了使用 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

【讨论】:

  • 可以测试vba程序,循环还没开始,说明数组为空
  • @jvdv OP 是完全正确的。如果您单步执行他们的代码并在 Watch 中查看 spl,您会看到它是 Dim'd 0 To -1
  • @jvdv 如果注释掉Split() 行,数组将未分配,for-loop 行会产生“for loop not initialized”错误92
  • “我很想知道你是否可以分配一个空数组。” “如果一个数组消耗了内存,就说它是分配的,有有效的下限和上限,并包含数据(即使该数据是数组数据类型的默认值,例如字符串类型变量数组的空字符串)。根据定义,静态数组总是分配的。" cpearson.com/excel/IsArrayAllocated.aspx
  • @im_chc,取决于你看的whereArrayListCollection 之间的推荐可以differ。我个人喜欢ArrayList。我很高兴它为你排序 =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2021-02-17
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多