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