Assign event handlers to controls on user form created dynamically in VBA into the sub

584 Views Asked by At

My question is related to this one. I created a class:

Public WithEvents btn As MSForms.CommandButton
    Private Sub btn_Click()
    MsgBox "Hello"
End Sub

The code below works well. I mean 10 buttons are displayed and after they are clicked, the message-box appears.

Dim collBtns As Collection

Public Sub UserForm_Initialize()

Dim btn As CommandButton
Dim btnH As cButtonHandler
Set collBtns = New Collection

For k = 1 To 10
    Set btn = testform.Controls.Add("Forms.CommandButton.1", True)
    With btn
        .Caption = "Title"
        .Left = 80
        .Width = 80
        .Top = 20 * k

        Set btnH = New cButtonHandler
        Set btnH.btn = btn
        collBtns.Add btnH
    End With
Next k

End Sub 

However, I need to use this procedure inside another procedure. The code below does not work.

Dim collBtns As Collection

Public Sub UserForm_Initialize()
Call Click100
End Sub

Public Sub Click100()

Dim btn As CommandButton
Dim btnH As cButtonHandler
Set collBtns = New Collection

For k = 1 To 10
    Set btn = testform.Controls.Add("Forms.CommandButton.1", True)
    With btn
        .Caption = "Title" 
        .Left = 80
        .Width = 80
         .Top = 20 * k

        Set btnH = New cButtonHandler
        Set btnH.btn = btn
        collBtns.Add btnH
    End With
Next k

End Sub
0

There are 0 best solutions below