vba 公共数组在子程序之间洗牌?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7693402/
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
Public array to shuffle values between subroutines?
提问by Felix
How do I get a public array whose values are set within a subroutine and do not get cleared at the end of the sub in which they were set?
如何获得一个公共数组,其值是在子程序中设置的,并且在设置它们的子程序的末尾不被清除?
I tried to get:
我试图得到:
Public GlobalArray() as Variant
Sub One()
ReDim GlobalArray(0 to 2)
GlobalArray=Array("0","1","2")
End Sub
Sub Two()
Check = GlobalArray(2)
End Sub
such that Check = 2, but I get thrown an error in sub Two complaining about a lack of values in GlobalArray (in fact, even sub One complains that there is no GlobalArray to put things in).
这样 Check = 2,但我在 sub Two 中抛出错误,抱怨 GlobalArray 中缺少值(实际上,即使 sub One 也抱怨没有 GlobalArray 可以放入东西)。
Basically, I have a procedure (One) pulling data from disparate sources, doing some stuff with it, letting the user do some things in Excel, and then running a new subroutine (Two) that uses both the user's input and some of the arrays from sub One.
基本上,我有一个过程(一)从不同的来源提取数据,用它做一些事情,让用户在 Excel 中做一些事情,然后运行一个新的子程序(二),它使用用户的输入和一些数组从子一。
回答by Reafidy
The Public GlobalArray() variable must be declared in a module. It will not work if it is declared at the top of either a Worksheet or the ThisWorkbook module. Try:
Public GlobalArray() 变量必须在模块中声明。如果它在 Worksheet 或 ThisWorkbook 模块的顶部声明,它将不起作用。尝试:
'// Must be declared in a module
Public GlobalArray() As Integer
'// These routines can be in worksheet/thisworkbook modules along side events etc Or in a module
Sub One()
ReDim GlobalArray(0 To 2)
GlobalArray(0) = 0
GlobalArray(1) = 1
GlobalArray(2) = 2
End Sub
Sub Two()
check = GlobalArray(2)
MsgBox (check)
End Sub
Instead of a public variable you could pass it to the second function:
您可以将它传递给第二个函数,而不是公共变量:
Sub One()
Dim GlobalArray(0 To 2) As Integer
GlobalArray(0) = 0
GlobalArray(1) = 1
GlobalArray(2) = 2
Two GlobalArrayToMe:=GlobalArray
End Sub
Sub Two(ByRef GlobalArrayToMe() As Integer)
check = GlobalArrayToMe(2)
MsgBox (check)
End Sub
回答by Jean-Fran?ois Corbett
This is not VBA and won't compile: GlobalArray=("0","1","2")
这不是 VBA,不会编译: GlobalArray=("0","1","2")
You could instead use: GlobalArray = Array("0", "1", "2")
您可以改为使用: GlobalArray = Array("0", "1", "2")
but that requires declaring Public GlobalArray() As Variant
但这需要声明 Public GlobalArray() As Variant
Otherwise assign the array elements one by one as in @Readfidy's answer.
否则,如@Readfidy 的回答一样,一一分配数组元素。