将事件处理程序分配给在VBA中dynamic创build的用户窗体上的控件到子项中

我的问题与这一个有关 。 我创build了一个类:

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

下面的代码运行良好。 我的意思是显示10个button,点击后,出现消息框。

 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 

但是,我需要在另一个程序中使用这个程序。 下面的代码不起作用。

 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