Excel 从用户窗体返回一个值
我试图将一个值从一个userform返回到另一个宏 下面是一段代码的示例,我想返回值Excel 从用户窗体返回一个值,excel,vba,userform,Excel,Vba,Userform,我试图将一个值从一个userform返回到另一个宏 下面是一段代码的示例,我想返回值intMonth: sub comparison() UserForm1.Show end sub 然后我得到了userform代码: Private Sub initialize() OptionButton1 = False End Sub Private Sub OptionButton1_Click() intMonth = 1 Me.Hide End Sub 如何将
intMonth
:
sub comparison()
UserForm1.Show
end sub
然后我得到了userform代码:
Private Sub initialize()
OptionButton1 = False
End Sub
Private Sub OptionButton1_Click()
intMonth = 1
Me.Hide
End Sub
如何将
1
的intMonth
值恢复到原始的comparison()
函数?这是一个简单的示例,但应该会有所帮助
在UserForm中:
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
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
实现所需功能的另一个有用方法是将代码包装到userform中的公共函数中 在UserForm中:
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
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
这样,函数负责显示userform,提示用户并返回值
如果调试此函数,您将看到在调用Me.Show()后,函数将停止并仅在用户窗体隐藏时继续,这在“确定”按钮中完成。您可以将
intMonth
设置为公共,或创建公共属性
,然后在调用代码中引用这些属性。做得好。我唯一的抱怨是将实例状态存储在表单的默认实例上,这是众所周知的,有时会导致各种问题。更深入的细节。(另外,选项基0
是默认值,…拥有它不会有什么坏处,但它在技术上是多余的)@MathieuGuindon Yep-如果重复调用比较
,并且没有编辑器重置单选按钮,则原样的代码也不会重置单选按钮:)。我试图让答案集中在OP的声明问题上,但同意你的观点。我的个人风格是Dim f as UserForm:set f=New UserForm
&c。谢谢你,我知道我现在做错了什么,我没有在UserForm代码中声明变量让它返回。我可以确认一下吗,你说的不是使用UserForm1.Show,而是应该在我的comparison()sub中创建一个UserForm实例?@MikeHill好消息!是,UserForm1。Show
可能会导致以后出现问题,因此比较
应该创建一个实例。上面由@MathieuGuindon链接的文章中的第二个代码示例显示了一个示例。快乐的黑客!是的,我读了一遍,我想我真的明白了。谢谢你的帮助