【发布时间】:2011-03-02 03:52:35
【问题描述】:
我想在运行时使用 VBA 在 Excel 中添加控件和关联事件,但我不知道如何添加事件。
我尝试了下面的代码,并且在我的用户表单中正确创建了按钮,但是应该显示 hello 消息的关联点击事件不起作用。
欢迎任何建议/更正。
Dim Butn As CommandButton
Set Butn = UserForm1.Controls.Add("Forms.CommandButton.1")
With Butn
.Name = "CommandButton1"
.Caption = "Click me to get the Hello Message"
.Width = 100
.Top = 10
End With
With ThisWorkbook.VBProject.VBComponents("UserForm1.CommandButton1").CodeModule
Line = .CountOfLines
.InsertLines Line + 1, "Sub CommandButton1_Click()"
.InsertLines Line + 2, "MsgBox ""Hello!"""
.InsertLines Line + 3, "End Sub"
End With
UserForm1.Show
【问题讨论】:
-
查看this answer,快速了解在 VBA 中使用运行时挂钩事件。
-
设计精美的问题。谢谢,有完全相同的疑问