动态标注 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.
这篇关于动态标注 VBA 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!