Assign public variable for option button on userform

YasserKhalil
PlatinumLounger
Posts: 4930
Joined: 31 Aug 2016, 09:02

Assign public variable for option button on userform

Post by YasserKhalil »

Hello everyone
I have three option buttons and there will be about 10 later. Trying to set public option button like that

Code: Select all

Private a, vOpt As MSForms.OptionButton

Private Sub Label9_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    If Not vOpt Is Nothing Then
        MsgBox vOpt.Name
    Else
        MsgBox "Option Button Not Selected."
    End If
End Sub

Private Sub UserForm_Initialize()
    If optName.Value = True Then
        Set vOpt = optName
    ElseIf optCode.Value = True Then
        Set vOpt = optCode
    ElseIf optID.Value = True Then
        Set vOpt = optID
    End If
End Sub
But I got the message all the time `Option Button Not Selected` even if any of the option buttons is selected. What I missed in the code?

YasserKhalil
PlatinumLounger
Posts: 4930
Joined: 31 Aug 2016, 09:02

Re: Assign public variable for option button on userform

Post by YasserKhalil »

I am sorry. This must not put in the userform initialzie
I have put it where I want exactly and worked

Code: Select all

Private a, vOpt As MSForms.OptionButton

Private Sub TextBox1_Change()
    Dim ctrl As MSForms.Control
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "OptionButton" Then
            If ctrl.Value = True Then Set vOpt = ctrl: Exit For
        End If
    Next ctrl
    If Not vOpt Is Nothing Then
        MsgBox vOpt.Name
    Else
        MsgBox "Option Button Not Selected", vbExclamation
    End If
End Sub