简体   繁体   English

动态标注VBA阵列?

[英]Dynamically Dimensioning A VBA Array?

Why am I unable to set the size of an array based on a variable? 为什么我无法根据变量设置数组的大小? What's the best way around this? 最好的方法是什么?

Dim NumberOfZombies as integer
NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) as New Zombie

You can use a dynamic array when you don't know the number of values it will contain until run-time: 如果在运行时之前不知道它将包含的值的数量,则可以使用动态数组

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)

Or you could do everything with one statement if you're creating an array that's local to a procedure: 或者,如果要创建一个过程本地的数组,则可以使用一个语句执行所有操作:

ReDim Zombies(NumberOfZombies) As Integer

Fixed-size arrays require the number of elements contained to be known at compile-time. 固定大小的数组需要在编译时知道包含的元素数。 This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time. 这就是为什么你不能使用变量来设置数组的大小 - 按定义,变量的值是可变的,只在运行时知道。

You could use a constant if you knew the value of the variable was not going to change: 如果您知道变量的值不会改变,则可以使用常量:

Const NumberOfZombies = 2000

but there's no way to cast between constants and variables. 但是没有办法在常量和变量之间进行转换。 They have distinctly different meanings. 它们有明显不同的含义。

You have to use the ReDim statement to dynamically size arrays. 您必须使用ReDim语句来动态调整数组大小。

Public Sub Test()
    Dim NumberOfZombies As Integer
    NumberOfZombies = 20000
    Dim Zombies() As New Zombie
    ReDim Zombies(NumberOfZombies)

End Sub

This can seem strange when you already know the size of your array, but there you go! 当你已经知道阵列的大小时,这看起来很奇怪,但你去了!

You can also look into using the Collection Object. 您还可以查看使用Collection Object。 This usually works better than an array for custom objects, since it dynamically sizes and has methods for: 这通常比自定义对象的数组更好,因为它动态调整大小并具有以下方法:

  • Add
  • Count 计数
  • Remove 去掉
  • Item(index) 项目(指数)

Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection. 此外,它通常更容易在集合中循环,因为您可以非常轻松地使用for ...每个结构与集合。

You need to use a constant. 你需要使用常量。

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies

or if you want to use a variable you have to do it this way: 或者如果你想使用变量,你必须这样做:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM