将事件处理程序分配给在VBA中动态创建的用户表单上的控件

时间:2015-06-26 16:32:30

标签: excel vba event-handling userform

我的问题与this one有关。我创建了一个类:

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

以下代码效果很好。我的意思是显示10个按钮,点击它们后,会出现信息框。

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

0 个答案:

没有答案