问题描述
Microsoft 站点建议以下代码应该可以工作:>
Dim numbers = {{1, 2}, {3, 4}, {5, 6}}
但是,当我尝试在 Excel VBA 模块中使用它时出现编译错误.以下确实适用于一维数组:
A = 数组(1, 2, 3, 4, 5)
但是,我还没有设法找到对 2D 数组执行相同操作的方法.有什么想法吗?
您还可以使用利用 Evaluate
函数和静态数组的速记格式.在下面的代码中,设置了 varData
,其中 []
是 Evaluate
函数和 {...}
表达式表示一个静态数组.每行以 ;
分隔,每个字段以 ,
分隔.它使您获得与 simoco 代码相同的最终结果,但语法更接近您的原始问题:
Sub ArrayShorthand()Dim varData As VariantDim intCounter1 作为整数Dim intCounter2 作为整数' 设置数组变量数据 = [{1, 2, 3;4、5、6;7, 8, 9}]' 测试对于 intCounter1 = 1 到 UBound(varData, 1)对于 intCounter2 = 1 到 UBound(varData, 2)Debug.Print varData(intCounter1, intCounter2)下一个 intCounter2下一个 intCounter1结束子
The Microsoft site suggests the following code should work:
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:
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?
You can also use a shorthand format leveraging the Evaluate
function and a static array. In the code below, varData
is set where []
is the shorthand for the Evaluate
function 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:
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
这篇关于如何在vba for excel中初始化多维数组变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!