The whole FAQ consists of four parts
the basics
automation events
some useful stuff
a substitute for control arrays in VBA (this one)
Unlike VB, it is not possible to create control arrays. However, it is possible to simulate some their functionality using WithEvents. I will show it for a userform named frmCol with two commandbuttons: cmd1 and cmd2.
We need a class to handle commandbuttonÆs events, one instance for each one commandbutton. It is easy to handle Click event in every instance, the clue is to pass event back to userform with additional information about which button was clicked. To do this, the class will keep information on what form is the parent and where to pass the back information. It is possible to work either with an array of objects or collection, I will use a collection.
LetÆs create a userform named frmCol with two commandbuttons: cmd1 and cmd2. Add a class module named cCB, note that m_Form is dimmed as a particular userform class:
[tt][color blue]Private WithEvents m_CB As MSForms.CommandButton
Private m_Form As frmCol
Public Sub Init(ctl As CommandButton, frm As frmCol)
Set m_CB = ctl
Set m_Form = frm
End Sub
Private Sub m_CB_Click()
m_Form.Info m_CB
End Sub
Private Sub Class_Terminate()
Set m_CB = Nothing
Set m_Form = Nothing
End Sub[/color][/tt]
An instance of this class should button click event (one instanceû one button), and keep information on userform that instantiated it.
The frmCol module:
[tt][color blue]Private colCB As New Collection
Private ctlCB As cCB
Private Sub UserForm_Initialize()
Set ctlCB = New cCB
ctlCB.Init cmd1, Me
colCB.Add ctlCB
Set ctlCB = New cCB
ctlCB.Init cmd2, Me
colCB.Add ctlCB
End Sub
Public Sub Info(ctl As MSForms.CommandButton)
MsgBox "click by: " & ctl.Caption
End Sub[/color][/tt]
Here we create a collection, instantiate ctlCB for each commandbutton and assign this button to ctlCB, together with a reference to current instance of userform. When the user clicks any button, appropriate instance of ctlCB traps the Click and calls Info procedure (a method of the frmCol) with a clicked button reference as an argument.
A situation similar to that in part I, where instead of rising event we could in the same way (i.e. userform with public procedure, instance of this userform passed to the custom class instance, call userformÆs procedure) inform userform about the event.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.