Search code examples
excelvbauserform

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?


Solution

  • 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