是否可以在 EXCEL VBA 中将多维数组作为参数传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13933025/
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
Is it possible to pass a multidimensional array as a parameter in EXCEL VBA?
提问by Marc L
I have an array created in one procedure which is the final results, I want to utilise these results in a new procedure as inputs to the calculations there. Is there a way to pass a multidimensional array as a parameter into another procedure? How would you you put it into the call and how woudl you define the parameter in the procedure it will be used in?
我在一个程序中创建了一个数组,这是最终结果,我想在新程序中利用这些结果作为那里计算的输入。有没有办法将多维数组作为参数传递给另一个过程?您将如何将其放入调用中以及如何在将要使用的过程中定义参数?
Thanks
谢谢
回答by Alex K.
Pass as you would a single dimension array by decorating the routine argument with parentheses;
通过用括号装饰例程参数,像传递单维数组一样传递;
sub a()
dim x(1, 1) As long
x(0, 0) = 1
x(1, 1) = 4
process x
end sub
sub process(arr() As long)
Msgbox arr(0, 0)
Msgbox arr(1, 1)
end sub
回答by Chris Harland
Is this the sort of thing you are after?
这是你追求的那种东西吗?
Sub AAATest()
''''''''''''''''''''''''
' Dynamic array to hold
' the result.
''''''''''''''''''''''''
Dim ReturnArr() As Long
Dim Ndx1 As Long
Dim Ndx2 As Long
Dim NumDims As Long
''''''''''''''''''''''''''
' call the function to get
' the result array.
''''''''''''''''''''''''''
ReturnArr = ReturnMulti()
NumDims = NumberOfArrayDimensions(Arr:=ReturnArr)
Select Case NumDims
Case 0
'''''''''''''''''''
' unallocated array
'''''''''''''''''''
Case 1
''''''''''''''''''''''''''
' single dimensional array
''''''''''''''''''''''''''
For Ndx1 = LBound(ReturnArr) To UBound(ReturnArr)
Debug.Print ReturnArr(Ndx1)
Next Ndx1
Case 2
'''''''''''''''''''''''''''
' two dimensional array
'''''''''''''''''''''''''''
For Ndx1 = LBound(ReturnArr, 1) To UBound(ReturnArr, 1)
For Ndx2 = LBound(ReturnArr, 2) To UBound(ReturnArr, 2)
Debug.Print ReturnArr(Ndx1, Ndx2)
Next Ndx2
Next Ndx1
Case Else
''''''''''''''''''''''
' too many dimensions
''''''''''''''''''''''
End Select
End Sub
Function ReturnMulti() As Long()
''''''''''''''''''''''''''''''''''''
' Returns a mutli-dimensional array.
''''''''''''''''''''''''''''''''''''
Dim A(1 To 2, 1 To 3) As Long
'''''''''''''''''''''''''''''
' put in some values.
'''''''''''''''''''''''''''''
A(1, 1) = 100
A(1, 2) = 200
A(1, 3) = 300
A(2, 1) = 400
A(2, 2) = 500
A(2, 3) = 600
ReturnMulti = A()
End Function