在下面的示例语法中,如何将每个元素添加到新数组而不是打印?我不确定怎么做,因为我不知道数组的大小,因为它可能是0(不需要初始化数组)或者它可能是它迭代的数组的Ubound
。 / p>
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
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:1)
它更简单:
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