我想使用Excel VBA将事件绑定到运行时的按钮。有没有像C#中的button.Click += button_Click
那样创建它的方法?
答案 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