Search code examples
excelvbacheckboxuserform

How to uncheck and suppress other checkboxs on a userform?


I have a userform with a lot of controls (Checkboxes , OptionButtons ,…).
But my concern here about only 3 checkboxes combined in one frame.
The names of the respective checkboxes are A1_CB , B2_CB , C3_CB
The cited checkboxes have a click event code either value of each CB is True or False.
I need at most only one check from them to be true on a time,
Meaning if A1_CB = True and I clicked B2_CB then both (A1_CB & C3_CB) = false ,
and If possible suppress codes of (A1_CB & C3_CB) when they are unchecked.

I tried this code but it has no effect and loop itself:

Private Sub A1_CB_Click()
 
    Me.B2_CB.Value = False
 
End Sub
 
Private Sub B1_CB_Click()
 
   Me.A1_CB.Value = False
 
End Sub

As always, grateful for all your help.


Solution

  • Your code dealing with the three text boxes should look like this:

    Option Explicit
    
    Private boolNoEvents As Boolean
    
    Private Sub A1_CB_Click()
        If Not boolNoEvents Then
            If Me.A1_CB.Value = True Then
              boolNoEvents = True
                Me.B2_CB.Value = False
                Me.C3_CB.Value = False
              boolNoEvents = False
            End If
            Debug.Print "A1_CB has been changed", Me.A1_CB.Value
        End If
    End Sub
    
    Private Sub B2_CB_Click()
         If Not boolNoEvents Then
            If Me.B2_CB.Value = True Then
                 boolNoEvents = True
                  Me.A1_CB.Value = False
                  Me.C3_CB.Value = False
                boolNoEvents = False
            End If
            Debug.Print "B2_CB has been changed", Me.B2_CB.Value
        End If
    End Sub
    
    Private Sub C3_CB_Click()
        If Not boolNoEvents Then
            If Me.C3_CB.Value = True Then
                 boolNoEvents = True
                    Me.A1_CB.Value = False
                    Me.B2_CB.Value = False
                boolNoEvents = False
            End If
            Debug.Print "C3_CB has been changed", Me.C3_CB.Value
        End If
    End Sub
    

    The above solution assumes that you want changing the other two check boxes value in False only if the respective check box is checked (each value becomes True)...