'Class module to handle CommandButton Events
Private WithEvents mobjCB As CommandButton
Private mlngIndex As Long
Private mobjParent As MyButtonsCollection
Public Property Set MyParentCollection(Value As MyButtonsCollection)
Set mobjParent = Value
End Property
Public Property Get Index() As Long
Index = mlngIndex
End Property
Public Property Let Index(ByVal Value As Long)
mlngIndex = Value
End Property
Public Property Get Button() As VB.CommandButton
Set Button = mobjCB
End Property
Public Property Set Button(ButtonControl As VB.CommandButton)
Set mobjCB = ButtonControl
End Property
Private Sub Class_Terminate()
Set mobjParent = Nothing
Set mobjCB = Nothing
End Sub
Private Sub mobjCB_Click()
mobjParent.RaiseButtonEvent Me
End Sub
'Collection class module to handle multiple buttons and to raise events to the Form.
'Omitted the typical Collection properties/methods like Count, Item etc..
Private mCol As Collection
Public Event ButtonClicked(Sender As MyButton)
Public Function Add(Button As VB.CommandButton, Index As Long, Optional sKey As String) As MyButton
'create a new object
Dim objNewMember As MyButton
Set objNewMember = New MyButton
Set objNewMember.Button = Button
objNewMember.Index = Index
If Len(sKey) = 0 Then
mCol.Add objNewMember
Else
mCol.Add objNewMember, sKey
End If
Set objNewMember.MyParentCollection = Me
'return the object created
Set Add = objNewMember
Set objNewMember = Nothing
End Function
Private Sub Class_Initialize()
Set mCol = New Collection
End Sub
Public Sub RaiseButtonEvent(ButtonObject As MyButton)
RaiseEvent ButtonClicked(ButtonObject)
End Sub
'Form Module
'Omitted the clean up code to Remove the Controls created at runtime, delete the collection etc...
Private WithEvents mcolButtons As MyButtonsCollection
Private Sub Form_Load()
Dim objButton As MyButton
Dim lngIdx As Long
Set mcolButtons = New MyButtonsCollection
For lngIdx = 0 To 63
Set objButton = mcolButtons.Add(Controls.Add("VB.CommandButton", "Command" & lngIdx), lngIdx, "Command" & lngIdx)
With objButton.Button
.Caption = "Command" & lngIdx
.Visible = True
.Move 0, 315 * lngIdx, 2000, 315
End With
Next
End Sub
Private Sub mcolButtons_ButtonClicked(Sender As MyButton)
Debug.Print Sender.Button.Caption, Sender.Index
End Sub