Arrays 动态填充VBA数组

Arrays 动态填充VBA数组,arrays,vba,ms-access,dynamic,ms-access-2013,Arrays,Vba,Ms Access,Dynamic,Ms Access 2013,在下面的示例语法中,如何将每个元素添加到新数组而不是打印?我不确定该怎么做,因为我不知道数组的大小,因为它可能是0(无需初始化数组),也可能是它正在迭代的数组的Ubound Option Compare Database Option Explicit Function TestIt() Dim animalarray As Variant, xyz As Variant animalarray = Array("Cat", "Cow", "Camel", "Dire Wolf", "Dog"

在下面的示例语法中,如何将每个元素添加到新数组而不是打印?我不确定该怎么做,因为我不知道数组的大小,因为它可能是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

您可以使用
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
更简单的是:

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

是否要添加到正在迭代的同一数组?@A.S.H-否,我要添加到新数组。很抱歉没有说清楚这太简单了,谢谢你!我从来都不能完全正确地使用“ReDim Preserve”语法,这就是每次都会弄乱我的语法的原因。在这种情况下,没有必要这样做!为了使我的语法能够根据需要工作,我必须为另一个数组的for Each块添加一个额外的If语句,因为数组中添加了不符合“C”标准的元素。因此,为了避免在For Each块中迭代这些数组,我添加了第二个If Left(…)语句来消除对它们的处理。@MichaelMormon您可以很容易地用一个空的
anotherArray
:just
Dim anotherArray()
开始代码。我理解您的问题的方式是,您需要一种通用机制来动态地将元素添加到数组中。我以为
Debug.Print
语句只是为了举例说明。。如果最终的目标是打印以“C”开头的名称,那么根本不需要另一个数组。我的意思是
Dim anotherArray():anotherArray=array()