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!
Asked
Active
Viewed 1,020 times
1
-
Including [this one](http://stackoverflow.com/questions/20890648/make-vba-code-work-for-all-boxes/20916544#20916544)? – Cool Blue Nov 22 '14 at 05:40
1 Answers
1
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.
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.

Dustin
- 401
- 3
- 4