vba 在多个子程序之间传递变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9203416/
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
passing variable value between multiple subroutines
提问by user793468
I have a Subroutine "Days" which has a variable Days. I want to pass values form that Days variable to a different subroutine "GetDays"
我有一个子程序“天”,它有一个变量天。我想将 Days 变量的值传递给不同的子程序“GetDays”
For eg:
例如:
Sub Day() Dim Days() as variant Days = Array(1,3,5,7,10,11) End Sub
Sub Day() Dim Days() 作为变体 Days = Array(1,3,5,7,10,11) End Sub
Sub GetDay() 'How do I get the values of Days here? End Sub
Sub GetDay() '我如何在这里获得天的值?结束子
回答by tpascale
Not completely sure I understand what you're after, but my best guess is that you want to set up a "DayClass" object that both holds the days values and returns them to other functions when they're needed:
不完全确定我明白你在追求什么,但我最好的猜测是你想设置一个“DayClass”对象,它既保存天数,又在需要时将它们返回给其他函数:
(1) in the VBA editor, insert a CLASSmodule
(1)在VBA编辑器中,插入一个CLASS模块
(2) in the properties window for this module, change the name to (say) DayClass(overriding the default name "Class1".)
(2) 在此模块的属性窗口中,将名称更改为(例如)DayClass(覆盖默认名称“Class1”。)
(3) put this code into the DayClass module:
(3) 将此代码放入DayClass模块中:
Private mDays As Variant ' member variable to hold the days array
' initialization method to populate the array
Private Sub Class_Initialize()
mDays = Array(1, 3, 5, 7, 10, 11)
End Sub
' little function to return a particular value from the array
Public Property Get Day(i As Long)
Day = mDays(i)
End Property
(4) To see the code above in action, insert a regular MODULE and put this little function in it, which may be invoked from the formula bar (if you want):
(4) 要查看上面的代码,请插入一个常规 MODULE 并将这个小函数放入其中,可以从公式栏调用(如果需要):
Public Function GetDays(i As Long)
Dim DC As New DayClass ' DC is dim'd of type DayClass
' so via DC you can get at whatever is in there
GetDays = DC.Day(i) ' this function returns the i'th value of the
' array in DayClass, via DayClass's "Get Day" property
End Function
(5) Since "GetDays" is a public function in a regular code module, you can test this out by entering the following formula into any spreadsheet cell:
(5) 由于“GetDays”是常规代码模块中的公共函数,您可以通过在任何电子表格单元格中输入以下公式来测试它:
=GetDays(3)
cell result = 7