动态标注 VBA 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4326678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically Dimensioning A VBA Array?
提问by sooprise
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
回答by Cody Gray
You can use a dynamic arraywhen 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 arraysrequire 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.
但是没有办法在常量和变量之间进行转换。它们具有明显不同的含义。
回答by Chris Spicer
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!
当您已经知道数组的大小时,这看起来很奇怪,但是您去了!
回答by Fink
You can also look into using the 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...each 结构用于集合。
回答by carny666
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)

