如何在Excel中初始化vba中的multidimensional arrayvariables

微软网站build议下面的代码应该工作:

Dim numbers = {{1, 2}, {3, 4}, {5, 6}}

但是,当我尝试在excel VBA模块中使用它时,我收到了一个complile错误。 以下工作适用于一维数组:

A = Array(1, 2, 3, 4, 5)

然而,我还没有设法find一种方法来做一个二维数组。 有任何想法吗?

您还可以使用利用Evaluate函数和静态数组的简写格式。 在下面的代码中, varData被设置,其中[]Evaluate函数的简写, {...}expression式指示静态数组。 每行用a分隔; 每个字段用a ,分隔。 它可以让你得到和simoco代码一样的最终结果,但是语法更贴近你原来的问题:

 Sub ArrayShorthand() Dim varData As Variant Dim intCounter1 As Integer Dim intCounter2 As Integer ' set the array varData = [{1, 2, 3; 4, 5, 6; 7, 8, 9}] ' test For intCounter1 = 1 To UBound(varData, 1) For intCounter2 = 1 To UBound(varData, 2) Debug.Print varData(intCounter1, intCounter2) Next intCounter2 Next intCounter1 End Sub 

微软网站build议…

这个build议对于VB.NET而不是VBA。

对于VBA你wehe在正确的方向。 你可以做:

 Dim A as Variant A = Array(Array(1, 2), Array(3, 4), Array(5, 6)) 

所以在这里你只需要告诉它的尺寸就可以生成没有任何内容的数组。 维度是X + 1,因为0作为数组中的一个位置。

 Dim MyArray(X, X) As Integer 

然后你用例子来填充它

 MyArray (0,0) = 1 MyArray (0,1) = 2 MyArray (1,0) = 3 MyArray (1,1) = 4 

等等。

如果你想要一个更方便的方式来填充它,你可以使用For Cycles,如果你要填充的数字有一个固有的逻辑。