vba 如何在vba for excel中初始化多维数组变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24584088/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:25:15  来源:igfitidea点击:

How to initialize a multidimensional array variable in vba for excel

arraysexcelvbaexcel-vba

提问by user3807215

The Microsoft sitesuggests the following code should work:

微软网站显示下面的代码应该工作:

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

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

However I get a complile error when I try to use it in an excel VBA module. The following does work for a 1D array:

但是,当我尝试在 Excel VBA 模块中使用它时出现编译错误。以下确实适用于一维数组:

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

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

However I have not managed to find a way of doing the same for a 2D array. Any ideas?

但是,我还没有设法找到对 2D 数组执行相同操作的方法。有任何想法吗?

回答by Robin Mackenzie

You can also use a shorthand format leveraging the Evaluatefunction and a static array. In the code below, varDatais set where []is the shorthand for the Evaluatefunction and the {...}expression indicates a static array. Each row is delimited with a ;and each field delimited with a ,. It gets you to the same end result as simoco's code, but with a syntax closer to your original question:

您还可以使用利用Evaluate函数和静态数组的速记格式。在下面的代码中,varData设置 where[]Evaluate函数的简写,{...}表达式表示一个静态数组。每行以 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

回答by Dmitry Pavliv

The Microsoft site suggests...

微软网站建议...

This suggestion is for VB.NET but not VBA.

此建议适用于 VB.NET,但不适用于 VBA。

For VBA you were in the right direction. You can do this:

对于 VBA,您的方向是正确的。你可以这样做:

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

回答by Maxi

So here you generate the array without anything on it, just by telling its dimensions. Dimension is X+1 because 0 counts as a position in the array.

所以在这里你生成一个没有任何东西的数组,只需告诉它的维度。维度是 X+1,因为 0 算作数组中的一个位置。

Dim MyArray(X, X) As Integer

Then you fill it by doing for exemple

然后你通过做例如填充它

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

...

...

And so on.

等等。

If you want a more convenient way of filling it you can use For Cycles if there is a inherent logic to the numbers you are filling it with.

如果您想要一种更方便的填充方式,则可以使用 For Cycles,前提是您填充的数字具有内在逻辑。