WithEvents for Toggle Button VBA

1k Views Asked by At

I am new to vba and need to make 32 toggle buttons for a game. I want to make use of withevents to have the code for the toggle buttons be all the same. I am unsure of how to do this and have looked at questions similar to this but they have not made sense. Your help is greatly appreciated!

1

There are 1 best solutions below

0
On

The first step in using the WithEvent process is to add all of the necessary objects to a collect to be preserved in memory for future use. Perform this step when the UserForm is Initialized.

In UserForm named UF:

Option Explicit

Dim ToggleControl As ToggleGroup
Dim Toggles As Collection

Private Sub UserForm_Initialize()
Dim oEach As Object

    Set Toggles = New Collection
    With UF
        For Each oEach In .Controls                        ' Loop through all the controls on the form
            If TypeName(oEach) Like "ToggleButton" Then    ' Verify that the object is a ToggleButton
                Set ToggleControl = New ToggleGroup        ' Create a new class object to assign the ToggleButton to
                Set ToggleControl.Action = oEach           ' Assign the ToggleButton (oEach) to the desired Class Action (Action)
                Toggles.add ToggleControl                  ' Add the Class to a collection to be preserved in memory
            End If
        Next oEach
    End With
End Sub

Next you will need to add a class to the project and name it ToggleGroup.

enter image description here

In the Class named ToggleGroup:

Option Explicit

Public WithEvents Action As MSForms.ToggleButton

Private Sub Action_Click()

    ' Perform Action ...

End Sub

This will create a custom event for the object when it is clicked. These custom events are executed prior to the native events which means that all of the native control events will still work.