vba 如何将用户窗体中 ComboBox 的值传递给宏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24015576/
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
How to pass value of ComboBox in userform to macro
提问by user3333621
I want to pass a value selected by user to be displayed in MsgBox. I write the following code but its display nothing.
我想传递用户选择的值以显示在 MsgBox 中。我编写了以下代码,但它什么也没显示。
Public Sub CommandButton1_Click()
SelectedCity = Me.ComboBox1.Value
DistSystem
End Sub
Sub DistSystem()
MsgBox (SelctedCity)
End Sub
采纳答案by SilverShotBee
Declare Selectedcity as a public OUTSIDE of the Sub
将 Selectedcity 声明为 Sub 的公共 OUTSIDE
Public SelectedCity as String
Public Sub CommandButton1_Click()
SelectedCity = Me.ComboBox1.Value
Call DistSystem
End Sub
Sub DistSystem()
MsgBox (SelectedCity)
End Sub
Obviously place DistSystem in a module!
显然将 DistSystem 放在一个模块中!
回答by Lukas2
Second procedure cannot read variable because of wrong scope. You have to declare SelectedCity variable as global:
由于范围错误,第二个过程无法读取变量。您必须将 SelectedCity 变量声明为全局变量:
Global SelectedCity
Public Sub CommandButton1_Click()
SelectedCity = Me.ComboBox1.Value
DistSystem
End Sub
Sub DistSystem()
MsgBox (SelctedCity)
End Sub
回答by Patrick Lepelletier
There are times when you can't pass it in an argument, but you can pass it here.
有时你不能在参数中传递它,但你可以在这里传递它。
Option Explicit 'forces to declare all variables
Public Sub CommandButton1_Click()
call DistSystem (Me.ComboBox1.Value)
'same as ( without call, and () ) :
' DistSystem Me.ComboBox1.Value
End Sub
Sub DistSystem(byval selectedCity$) 'same as: byval SelectedCity as string
MsgBox SelectedCity
End Sub
This works even if DistSystem
is in a different module.
即使DistSystem
在不同的模块中,这也有效。