|
|
|
|
|
|
Excel
|
Group All Toggle Buttons on a Userform
|
|
Ease of Use
|
Hard
|
Version tested with
|
2002
|
Submitted by:
|
Jacob Hilderbrand
|
Description:
|
Group all Toggle Buttons and write code that will apply to every member of the group instead of writing code for each specific Toggle Button.
|
Discussion:
|
You are making a userform with many Toggle Buttons. In this example we have the beginnings of a Keno game with 80 Toggle Buttons. You need code to run whenever any Toggle Button is pressed, but you don't want to repeat that code 80 times (once for each Toggle Button). A Class module will allow you to group all Toggle Buttons and write one macro that will be applied to every Toggle Button.
|
Code:
|
instructions for use
|
Option Explicit
Public WithEvents ToggleGroup As ToggleButton
Private Sub ToggleGroup_Change()
MsgBox "You pressed " & ToggleGroup.Caption & vbCrLf & _
ToggleGroup.Caption & " now has a value of " & ToggleGroup.Value
End Sub
Private Sub ToggleGroup_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
Userform1.Label1.Caption = ToggleGroup.Caption & " - " & ToggleGroup.Value
End Sub
Option Explicit
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
ToggleCount = ToggleCount + 1
ReDim Preserve Buttons(1 To ToggleCount)
Set Buttons(ToggleCount).ToggleGroup = Ctl
End If
Next Ctl
End Sub
Option Explicit
Private Sub CommandButton1_Click()
UserForm1.Show
End Sub
|
How to use:
|
- Open Excel.
- Press Alt + F11 to open VBE.
- Insert | Class Module.
- Paste the code from above (The section marked for the Class Module Only).
- Insert | Userform.
- Double Click the userform to view the code section and paste the code from above (The section marked for the UserForm Only).
- Add as many Toggle Buttons to the User Form as you would like. Add Toggle Buttons from the Control Toolbox.
- Add one label from the Control Toolbox - it identifies the toggle button value on mouse over.
- Double click the Sheet1 Module in the left-hand pane.
- Paste in the Code marked For Worksheet of Choice.
- Close the VBE (using the red X button or Alt + Q)
|
Test the code:
|
- Go to the worksheet that you put the For Worksheet of Choice code into.
- From the View menu select Toolbars > Control Toolbox. With the Control Toolbox visible, drag a command button onto your worksheet. Exit Design mode by clicking the little cyan-colored triangle button.
- Press the command button on the worksheet. The Userform should now be visible.
|
Sample File:
|
ClassModuleToggleButton.ZIP 11.14KB
|
Approved by mdmackillop
|
This entry has been viewed 154 times.
|
|