在 Excel 表单中动态添加控件事件;您需要首先在类模块中添加事件。对于我的示例,我将添加一个名为 clsTEST 的类模块,其中包含一个事件 btn_click()
'#### CLASS NAMED clsTEST
Public WithEvents btn As MSForms.CommandButton
Public frm As UserForm
Dim iCount As Long
Private Sub btn_Click()
iCount = IIf(iCount < 1, 1, iCount + 1)
btn.Caption = "Count " & Str(iCount)
End Sub
'### END CLASS
正如您所看到的,唯一要做的就是将按钮上的标题设置为您单击它的次数。接下来,在表单代码中输入以下内容:
Dim mColButtons As New Collection '## SET A NEW COLLECTION
Private Sub UserForm_Activate()
'
Dim btnEvent As clsTEST
Dim ctl As MSForms.Control
'
Set ctl = Me.Controls.Add("Forms.CommandButton.1")
'
With ctl
.Caption = "XYZ"
.Name = "AButton"
END With
'
Set btnEvent = new clsTEST
Set btnEvent.btn = ctl
set btnEvent.frm = Me
'
mColButtons.add btnEvent
'End Sub
当您激活表单时,它将创建一个按钮。每次单击按钮时,标题都会更改。