Search code examples
excelvbatogglebutton

How to allow only one ToggleButton to be ON at a time in Excel


I have created a UserForm in excel 2010 and put 10 toggle button in it.When I run the form all of them can be ON (value = TRUE) but I want only one of them to be ON at the same time.Like below:

In A Class Module

Public WithEvents ToggleGroup As ToggleButton 

Private Sub ToggleGroup_click() 

' code

End Sub 

In a UserForm

Dim Buttons() As New Class1 

Private Sub UserForm_Initialize() 

    Dim ToggleCount     As Integer 
    Dim Ctl             As Control 

    For Each Ctl In UserForm1.Controls 
        If TypeName(Ctl) = "ToggleButton" Then 
            ReDim Preserve Buttons(1 To ToggleCount) 
            Set Buttons(ToggleCount).ToggleGroup = Ctl 
        End If 
    Next Ctl 

End Sub

In a Module

Sub Form()
UserForm1.Show
End Sub

Solution

  • To use a Toggle button you could try this method:

    Create a number of Toggle controls and use the Tag property to group your buttons.
    The code below will then compare the name and tag of each control. All toggle buttons with the same tag will be made the opposite of the one that was clicked.

    Private Sub Toggle1_Click()
        ToggleClick Me.ActiveControl
    End Sub
    
    Private Sub Toggle2_Click()
        ToggleClick Me.ActiveControl
    End Sub
    
    Private Sub Toggle3_Click()
        ToggleClick Me.ActiveControl
    End Sub
    
    Private Sub Toggle4_Click()
        ToggleClick Me.ActiveControl
    End Sub
    
    Private Sub ToggleClick(ClickedControl As Control)
    
        Dim Ctl As Control
    
        For Each Ctl In Me.Controls
            If TypeName(Ctl) = "ToggleButton" Then
                If Ctl.Name <> ClickedControl.Name And Ctl.Tag = ClickedControl.Tag Then
                    Ctl.Value = Not ClickedControl.Value
                End If
            End If
        Next Ctl
    
    End Sub