PDA

View Full Version : Toggle Button Click



sam314159
10-04-2010, 06:11 AM
I have a user form with 64 toggle buttons and I need to run the same subroutine regardless of which one is clicked. Is there a way to do this without having to write 64 tg_Click()?

Maybe I am looking at this the wrong way.

deyken
10-04-2010, 06:32 AM
Hi There,

If you can send me a demo of what you have I might be able to give you a detailed solution, however:

a) If you need a sub routine to run upon the clicking of a toggle button, you could declare a central private sub or function (with or without arguments) and simply call the same function/Sub upon every click event, merely changing the argument included in the (), like this:

Private Sub ToggleButton1_Click()
DoSomething (1) ' Here you simply include the integer 1, 2, 3 etc. in the parenthesis

End Sub
Function DoSomething(i As Integer)
Select Case i
Case 1
' run the function, but now we know that Toggle Button 1 was clicked
Case 2
' run the function, but now we know that Toggle Button 2 was clicked
End Select
End Function

or

b) If you want the same thing to happen regardless of the toggle button clicked by the user, simply call a central Function/Sub name.

Either way you could simply Copy/Paste the function call code into the OnClick event of all 64 buttons...

sam314159
10-04-2010, 06:49 AM
Thanks Deyken. I am calling the exat same function regardless of which toggle button was clicked so option 2 is probably more suitable for me.

I was looking for a way to avoid copying and pasting 64 times but that's not a huge deal.

deyken
10-04-2010, 07:10 AM
Hi Sam,

What do the 64 Toggle buttons need to do? Does the outcome of the function/routine differ based on the toggle button clicked? Perhaps there is a way to avoid pasting 64 times, but this would depend on the work that the Click_event needs to perform and the desired output...

Let me know...

JKwan
10-04-2010, 12:15 PM
OK, try this with a class
1) add a class module and call it clsToggleButtons
put the following into the class

Private WithEvents cmbToggleCommandButton As MSForms.ToggleButton
Sub SetToggleCommandButton(ByVal cmb As MSForms.ToggleButton)
Set cmbToggleCommandButton = cmb
End Sub
Private Sub cmbToggleCommandButton_Click()
With cmbToggleCommandButton
MsgBox "I am doing the same thing with - " & cmbToggleCommandButton.Name

End With
End Sub

2) - put the following into your form module

Option Explicit
Dim ToggleButtons() As clsToggleButtons
Private Sub UserForm_Initialize()
Dim ToggleButtonControl As MSForms.Control
Dim ToggleButtonNumber As Long
For Each ToggleButtonControl In Me.Controls
If TypeName(ToggleButtonControl) = "ToggleButton" Then
ToggleButtonNumber = ToggleButtonNumber + 1
ReDim Preserve ToggleButtons(ToggleButtonNumber)
Set ToggleButtons(ToggleButtonNumber) = New clsToggleButtons
ToggleButtons(ToggleButtonNumber).SetToggleCommandButton ToggleButtonControl
ToggleButtonControl.Tag = ToggleButtonNumber
End If
Next
End Sub