Return a value from a userform

那年仲夏 提交于 2021-01-28 12:53:45

问题


I am trying to return a value from a userform to another macro.

Here is an example of a piece of code that I want to return the value intMonth:

sub comparison()
    UserForm1.Show
end sub

then I have the userform code:

Private Sub initialize()
    OptionButton1 = False
End Sub

Private Sub OptionButton1_Click()
    intMonth = 1
    Me.Hide
End Sub

How do I get the intMonth value of 1 back to my original comparison() function?


回答1:


This is a minimal example, but should help.

In the 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

In a module or ThisWorkbook:

Option Explicit
Option Base 0

Sub comparison()
    UserForm1.Show
    MsgBox CStr(UserForm1.intMonth)   ' <-- retrieve the value
End Sub



回答2:


Another useful way to achieve what you need is to wrap the code in a public function in the userform.

In the UserForm:

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

Then in module, it is simple as this:

Option Explicit
Option Base 0

Sub comparison()
    MsgBox Userform1.Choose_Option() 
End Sub

This way, the function is in charge of showing the userform, prompting the user and returning the value.

If you debug this function, you will see that after Me.Show() is called, the function halts and continue only when the userform is hidden, which is done in the OK button.



来源:https://stackoverflow.com/questions/51952304/return-a-value-from-a-userform

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!