如何将Click事件设置为Excel VBA中代码隐藏中的按钮?

时间:2017-09-06 21:34:07

标签: excel-vba events vba excel

我想使用Excel VBA将事件绑定到运行时的按钮。有没有像C#中的button.Click += button_Click那样创建它的方法?

1 个答案:

答案 0 :(得分:0)

此例程在运行时向已存在的Userform1添加一个按钮和一个按钮单击事件。请注意,您需要设置对Microsoft Visual Basic For Applications Extensibility 5.3(工具|参考)

的引用
Sub AddControlDynamically()

Dim vbCompFrm As VBComponent
Dim objButton As Object

'Edit "Userform1" in the following line to your Userform name
Set vbCompFrm = ThisWorkbook.VBProject.VBComponents("Userform1")

'Following line creates a command button on the form
Set objButton = vbCompFrm.Designer.Controls.Add("Forms.CommandButton.1")

With objButton
    .Name = "cmdButton1"   'Can use this name for the Add event sub
    .Left = 10
    .Top = 10
    .Height = 20
    .Width = 80
    .Caption = "My Button"
End With

With vbCompFrm.CodeModule
    .InsertLines .CountOfLines + 1, "Private Sub cmdButton1_Click()"
    .InsertLines .CountOfLines + 1, "    MsgBox ""Hello World!"""
    .InsertLines .CountOfLines + 1, "End Sub"
End With

End Sub