Mike Hill
Mike Hill

Reputation: 123

Return a value from a userform

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?

Upvotes: 3

Views: 14515

Answers (2)

Pedrusco
Pedrusco

Reputation: 31

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.

Upvotes: 0

cxw
cxw

Reputation: 17041

This is a minimal example, but should help.

screenshot of UserForm

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

Upvotes: 5

Related Questions