I have around 100 ToggleButtons.
I would like:
If .value = true then
togglebuttons.BackColor = vbRed
Else
= vbGreen
I can write the code for every one, but is there a way to create a group or class so that color change code would be applied to all of them?
-Excel365
Here's an example that creates a new class in order to handle multiple toggle buttons using one event handler. Note that it assumes that the first page of your multipage control contains your toggle buttons. Change the page reference accordingly.
First insert a new class module (Insert >> Class Module), and name it clsToggleButton.
Then copy and paste the following code into the code module for your new class . . .
Option Explicit
Public WithEvents toggleButton As MSForms.toggleButton
Private Sub toggleButton_Click()
With toggleButton
If .Value = True Then
.BackColor = vbRed
Else
.BackColor = vbGreen
End If
End With
End Sub
Then copy and paste the following code into your userform code module . . .
Option Explicit
Dim toggleButtonCollection As Collection
Private Sub UserForm_Initialize()
Set toggleButtonCollection = New Collection
Dim ctrl As MSForms.Control
Dim cToggleButton As clsToggleButton
For Each ctrl In Me.MultiPage1.Pages(0).Controls
If TypeName(ctrl) = "ToggleButton" Then
'ctrl.BackColor = vbGreen 'uncomment to initially set the backcolor to green
Set cToggleButton = New clsToggleButton
Set cToggleButton.toggleButton = ctrl
toggleButtonCollection.Add cToggleButton
End If
Next ctrl
End Sub