Return 来自用户表单的值
Return a value from a userform
我正在尝试 return 从用户窗体到另一个宏的值。
这是我想要 return 值 intMonth
:
的一段代码示例
sub comparison()
UserForm1.Show
end sub
然后我有用户表单代码:
Private Sub initialize()
OptionButton1 = False
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
Me.Hide
End Sub
如何将 1
的 intMonth
值返回到我原来的 comparison()
函数?
这是一个最小的示例,但应该有所帮助。
在用户窗体中:
Option Explicit
Option Base 0
Public intMonth As Long ' <-- the variable that will hold your output
Private Sub initialize()
OptionButton1 = False
intMonth = 0
End Sub
Private Sub CommandButton1_Click() ' OK button
Me.Hide
End Sub
Private Sub OptionButton1_Click()
intMonth = 1 '<-- set the value corresponding to the selected radio button
End Sub
Private Sub OptionButton2_Click()
intMonth = 2
End Sub
在模块中或 ThisWorkbook
:
Option Explicit
Option Base 0
Sub comparison()
UserForm1.Show
MsgBox CStr(UserForm1.intMonth) ' <-- retrieve the value
End Sub
实现所需功能的另一种有用方法是将代码包装在用户窗体的 public 函数中。
在用户窗体中:
Option Explicit
Option Base 0
Private intMonth As Long
Public Function Choose_Option()
OptionButton1 = False
intMonth = 0
Me.show()
Choose_Option = intMonth
End sub
Private Sub CommandButton1_Click() ' OK button
Me.Hide
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
End Sub
Private Sub OptionButton2_Click()
intMonth = 2
End Sub
然后在模块中,就这么简单:
Option Explicit
Option Base 0
Sub comparison()
MsgBox Userform1.Choose_Option()
End Sub
这样,该函数负责显示用户表单、提示用户并返回值。
如果你调试这个函数,你会看到在调用 Me.Show() 之后,函数停止并仅在隐藏用户窗体时继续,这是在确定按钮中完成的。
我正在尝试 return 从用户窗体到另一个宏的值。
这是我想要 return 值 intMonth
:
sub comparison()
UserForm1.Show
end sub
然后我有用户表单代码:
Private Sub initialize()
OptionButton1 = False
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
Me.Hide
End Sub
如何将 1
的 intMonth
值返回到我原来的 comparison()
函数?
这是一个最小的示例,但应该有所帮助。
在用户窗体中:
Option Explicit
Option Base 0
Public intMonth As Long ' <-- the variable that will hold your output
Private Sub initialize()
OptionButton1 = False
intMonth = 0
End Sub
Private Sub CommandButton1_Click() ' OK button
Me.Hide
End Sub
Private Sub OptionButton1_Click()
intMonth = 1 '<-- set the value corresponding to the selected radio button
End Sub
Private Sub OptionButton2_Click()
intMonth = 2
End Sub
在模块中或 ThisWorkbook
:
Option Explicit
Option Base 0
Sub comparison()
UserForm1.Show
MsgBox CStr(UserForm1.intMonth) ' <-- retrieve the value
End Sub
实现所需功能的另一种有用方法是将代码包装在用户窗体的 public 函数中。
在用户窗体中:
Option Explicit
Option Base 0
Private intMonth As Long
Public Function Choose_Option()
OptionButton1 = False
intMonth = 0
Me.show()
Choose_Option = intMonth
End sub
Private Sub CommandButton1_Click() ' OK button
Me.Hide
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
End Sub
Private Sub OptionButton2_Click()
intMonth = 2
End Sub
然后在模块中,就这么简单:
Option Explicit
Option Base 0
Sub comparison()
MsgBox Userform1.Choose_Option()
End Sub
这样,该函数负责显示用户表单、提示用户并返回值。
如果你调试这个函数,你会看到在调用 Me.Show() 之后,函数停止并仅在隐藏用户窗体时继续,这是在确定按钮中完成的。