相关疑难解决方法(0)

如何将事件添加到使用VBA在Excel中运行时创建的控件

我想在运行时在Excel中使用VBA添加一个Control和一个关联的事件,但我不知道如何添加事件.

我尝试了下面的代码,并且在我的userform中正确创建了Button,但是应该显示hello消息的关联click事件不起作用.

任何建议/更正都会受到欢迎.

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
Run Code Online (Sandbox Code Playgroud)

events controls vba

15
推荐指数
3
解决办法
5万
查看次数

标签 统计

controls ×1

events ×1

vba ×1