Chadi N
Chadi N

Reputation: 441

Unselect an entire optionbutton group if another optionbutton outside the group is selected

I have optionbutton1 and optionbutton2.

I also have a 8 others optionbuttons grouped under the groupname "category".

I want to deselect any optionbutton from the groupname "category" If OptionButton1.Value = True Or Optionbutton2.Value = True.

I tried this, but it's doesn't work and it's way too long. There must be another way

Private Sub OptionButton1_Click()
If OptionButton1.Value = True Or OptionButton2.Value = True Then OptionButton4.Value = False And OptionButton5.Value = False And OptionButton6.Value = False And _
OptionButton7.Value = False And OptionButton8.Value = False And OptionButton9.Value = False And OptionButton10.Value = False And OptionButton11.Value = False

End Sub

Upvotes: 0

Views: 501

Answers (1)

Domenic
Domenic

Reputation: 8114

First, there's no need for your If statement, since the first condition will always evaluate to True when OptionButton1 is clicked. Secondly, each statement that sets an option button to False should be on a separate line, and without the And operator. Try the following instead...

Private Sub OptionButton1_Click()
        OptionButton4.Value = False
        OptionButton5.Value = False
        OptionButton6.Value = False
        OptionButton7.Value = False
        OptionButton8.Value = False
        OptionButton9.Value = False
        OptionButton10.Value = False
        OptionButton11.Value = False
End Sub

However, here's an alternative...

Private Sub OptionButton1_Click()

    Dim ctrl As MSForms.Control
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "OptionButton" Then
            If ctrl.GroupName = "Category" Then
                ctrl.Value = False
            End If
        End If
    Next ctrl

End Sub

Actually, since you want to reset the "Category" option buttons when OptionButton1 or OptionButton2 is clicked, try the following instead...

Private Sub OptionButton1_Click()
   Call ResetCategoryOptionButtons
End Sub

Private Sub OptionButton2_Click()
   Call ResetCategoryOptionButtons
End Sub

Private Sub ResetCategoryOptionButtons()
    Dim ctrl As MSForms.Control
    For Each ctrl In Me.Controls
        If TypeName(ctrl) = "OptionButton" Then
            If ctrl.GroupName = "Category" Then
                ctrl.Value = False
            End If
        End If
    Next ctrl
End Sub

Hope this helps!

Upvotes: 1

Related Questions