Toggle Button Events Class
Using a class module to control events of multiple controls has been discusses a number of times on this site and elsewhere. But whenever I do it for a new control, I'm going to post it. The control of the day is the Toggle button. Start by creating a class module and calling it CToggles. In the class module, put the following code:
Property Set ToggleButtn(oButton As MSForms.ToggleButton)
Set mToggle = oButton
End Property
Property Get ToggleButtn() As MSForms.ToggleButton
Set ToggleButtn = mToggle
End Property
Private Sub mToggle_Click()
'Put your own meaningful event code here
If mToggle.Caption = "1" Then
mToggle.Caption = "2"
Else
mToggle.Caption = "1"
End If
End Sub
In a standard module, put this code:
Public gToggles() As CToggles
Sub AddTogglesToClass()
Dim oleToggle As OLEObject
Dim i As Long
i = 1
'Loop through all the oleobjects and add the toggles to the array
For Each oleToggle In Sheet1.OLEObjects
If TypeName(oleToggle.Object) = "ToggleButton" Then
ReDim Preserve gToggles(1 To i)
Set gToggles(i) = New CToggles
Set gToggles(i).ToggleButtn = oleToggle.Object
i = i + 1
End If
Next oleToggle
End Sub
Run AddTogglesToClass to get all the ToggleButtons from Sheet1 into the class and thus hooked into the event. You can code whatever you want in the Click event or use any other events available.
For more information, see J-Walk and Associates' Developer Tip #44 and JKP Application Development Service's Control Events Article.
Doug Glancy:
Dick,
Can you explain the purpose of the Let and Get in the Class module? I think it would work the same without them. Also, I learned to do this adding the controls to a collection rather than an array. Do you know if one is preferable over the other?
Thanks,
Doug
23 August 2005, 10:49 pmJuan Pablo González:
Doug,
Maybe this post will explain it a bit ? Dick took quite a hit the last time for not using "proper" coding techniques
http://www.dicks-blog.com/archives/2005/05/23/getting-data-from-a-userform/
24 August 2005, 3:26 pmDoug Glancy:
Juan,
Thanks. I figured Stephen and company were probably to blame . I've switched my behavior with userforms after reading Chapter 10.
It seems to me this is a little different because the class is a class of togglebuttons already. If the code was changed to use checkboxes instead, then you'd need an analogous class of checkboxes. I don't understand how the Lets/Gets inside the class make it more insulated. Wouldn't the encapsulation actually have to be in the standard module so that you could switch from a togglebutton class to a checkbox class?
I'm over my head here, but just wondering.
Doug
24 August 2005, 4:02 pm