动态填充VBA阵列 [英] Dynamically Populate VBA Array

查看:196
本文介绍了动态填充VBA阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例语法中,如何将每个元素添加到新数组而不是打印?我不确定如何做,因为我不知道数组的大小,因为它可以是0(不需要初始化数组),或者它可以是 Ubound

In the example syntax below, how can I add each element to a new array instead of printing? I am unsure how to do such as I would not know the size of the array, since it could be 0 (no need to ever initialize the array) or it could be the Ubound of the array it is iterating.

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

这篇关于动态填充VBA阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆