动态填充VBA数组(Dynamically Populate VBA Array)

2019-09-29 20:11发布

在下面的示例语法,我怎样才能每个元素添加到新的数组,而不是印刷? 我不确定该怎么做,例如我不知道该数组的大小,因为它可能是0(无需曾经初始化数组),或者它可能是Ubound它遍历数组。

Option Compare Database
Option Explicit

Function TestIt()
Dim animalarray As Variant, xyz As Variant
animalarray = Array("Cat", "Cow", "Camel", "Dire Wolf", "Dog", "Coyote", "Rabbit", "Road runner", "Cougar")

For Each xyz In animalarray
  If Left(CStr(xyz), 1) = "C" Then
    Debug.Print CStr(xyz)
  End If
Next

End Function

Answer 1:

您可以使用Redim Preserve

Sub TestIt()
    Dim animalArray(): animalArray = Array("Cat", "Cow", "Camel", "Dire Wolf", "Dog", "Coyote", "Rabbit", "Road runner", "Cougar")
    Dim anotherArray(): anotherArray = Array("Lion", "Tiger", "Leopard")

    Dim xyz As Variant
    For Each xyz In animalArray
      If Left(CStr(xyz), 1) = "C" Then
        ReDim Preserve anotherArray(UBound(anotherArray) + 1)
        anotherArray(UBound(anotherArray)) = xyz
      End If
    Next

    For Each xyz In anotherArray
        Debug.Print xyz
    Next
End Sub


Answer 2:

这是更简单:

Function TestIt()

    Dim animalarray As Variant
    Dim newarray As Variant
    Dim xyz As Variant

    animalarray = Array("Cat", "Cow", "Camel", "Dire Wolf", "Dog", "Coyote", "Rabbit", "Road runner", "Cougar")
    newarray = animalarray

    For Each xyz In newarray
        If Left(CStr(xyz), 1) = "C" Then
            Debug.Print CStr(xyz)
        End If
    Next

End Function


文章来源: Dynamically Populate VBA Array