如何将userform中的ComboBox值传递给宏

时间:2014-06-03 12:46:15

标签: excel-vba vba excel

我想传递用户选择的值以显示在MsgBox中。我写下面的代码,但它没有显示。

Public Sub CommandButton1_Click()
    SelectedCity = Me.ComboBox1.Value
    DistSystem
End Sub

Sub DistSystem()
    MsgBox (SelctedCity)
End Sub

3 个答案:

答案 0 :(得分:0)

由于范围错误,第二个程序无法读取变量。 您必须将SelectedCity变量声明为global:

Global SelectedCity

Public Sub CommandButton1_Click()

SelectedCity = Me.ComboBox1.Value
DistSystem

End Sub

Sub DistSystem()

MsgBox (SelctedCity)

End Sub

答案 1 :(得分:0)

有些时候你无法在论证中传递它,但你可以在这里传递它。

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

即使DistSystem位于不同的模块中,这也有效。

答案 2 :(得分:-1)

将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

显然将DistSystem放在模块中!