Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 动态标注VBA数组的尺寸?_Arrays_Vba - Fatal编程技术网

Arrays 动态标注VBA数组的尺寸?

Arrays 动态标注VBA数组的尺寸?,arrays,vba,Arrays,Vba,为什么我不能基于变量设置数组的大小?最好的解决办法是什么 Dim NumberOfZombies as integer NumberOfZombies = 20000 Dim Zombies(NumberOfZombies) as New Zombie 你需要使用一个常数 CONST NumberOfZombies = 20000 Dim Zombies(NumberOfZombies) As Zombies 或者,如果要使用变量,则必须这样做: Dim NumberOfZombies As

为什么我不能基于变量设置数组的大小?最好的解决办法是什么

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

你需要使用一个常数

CONST NumberOfZombies = 20000
Dim Zombies(NumberOfZombies) As Zombies
或者,如果要使用变量,则必须这样做:

Dim NumberOfZombies As Integer
NumberOfZombies = 20000

Dim Zombies() As Zombies

ReDim Zombies(NumberOfZombies)

在运行时之前不知道动态数组将包含多少值时,可以使用动态数组

Dim Zombies() As Integer
ReDim Zombies(NumberOfZombies)
或者,如果要创建过程的本地数组,则可以使用一条语句执行所有操作:

ReDim Zombies(NumberOfZombies) As Integer
固定大小数组要求在编译时已知包含的元素数。这就是为什么不能根据定义使用变量来设置数组的大小,变量的值是可变的,只有在运行时才知道

如果知道变量的值不会改变,则可以使用常量:

Const NumberOfZombies = 2000

但是没有办法在常量和变量之间转换。它们的含义截然不同。

您必须使用ReDim语句动态调整数组大小

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

End Sub

当你已经知道你的数组的大小时,这看起来很奇怪,但是你做到了

您还可以研究如何使用Collection对象。这通常比自定义对象的数组工作得更好,因为它可以动态调整大小并具有以下方法:

  • 计数
  • 除去
  • 项目(索引)

另外,通常在集合中循环也比较容易,因为可以很容易地在集合中使用for…each结构。

是否有更整洁的方法将NumberOfZombies转换为维度定义中的CONST right?Dim Zombies(CONST NumberOfZombies)作为新的zombie我在完成键入之前提交了我的答案。哦,我明白了,所以如果使用了Redim,可以使用一个变量来定义维度,这有助于了解,谢谢!但这是一个错误的答案
ReDim Zombies(NumberOfZombies)
将声明一个带有
NumberOfZombies+1
元素的数组,而不仅仅是
NumberOfZombies