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

Fre*_*CHE 15 events controls vba

我想在运行时在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)

小智 20

在运行时添加按钮然后添加事件的代码真的很简单,因为很难找到..我可以说,因为我花了更多的时间在这个困惑上并且比其他任何事情都更加烦躁编程..

创建一个Userform并输入以下代码:

Option Explicit


Dim ButArray() As New Class2

Private Sub UserForm_Initialize()
    Dim ctlbut As MSForms.CommandButton

    Dim butTop As Long, i As Long

    '~~> Decide on the .Top for the 1st TextBox
    butTop = 30

    For i = 1 To 10
        Set ctlbut = Me.Controls.Add("Forms.CommandButton.1", "butTest" & i)

        '~~> Define the TextBox .Top and the .Left property here
        ctlbut.Top = butTop: ctlbut.Left = 50
        ctlbut.Caption = Cells(i, 7).Value
        '~~> Increment the .Top for the next TextBox
        butTop = butTop + 20

        ReDim Preserve ButArray(1 To i)
        Set ButArray(i).butEvents = ctlbut
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)

现在你需要为你的项目代码添加一个类模块.请记住它的类模块而不是Module.And输入以下简单代码(在我的例子中类名是Class2) -


Public WithEvents butEvents As MSForms.CommandButton

Private Sub butEvents_click()

    MsgBox "Hi Shrey"

End Sub
Run Code Online (Sandbox Code Playgroud)

而已.现在运行它


小智 5

尝试这个:

Sub AddButtonAndShow()

    Dim Butn As CommandButton
    Dim Line As Long
    Dim objForm As Object

    Set objForm = ThisWorkbook.VBProject.VBComponents("UserForm1")

    Set Butn = objForm.Designer.Controls.Add("Forms.CommandButton.1")
    With Butn
        .Name = "CommandButton1"
        .Caption = "Click me to get the Hello Message"
        .Width = 100
        .Top = 10
    End With

    With objForm.CodeModule
        Line = .CountOfLines
        .InsertLines Line + 1, "Sub CommandButton1_Click()"
        .InsertLines Line + 2, "MsgBox ""Hello!"""
        .InsertLines Line + 3, "End Sub"
    End With

    VBA.UserForms.Add(objForm.Name).Show

End Sub
Run Code Online (Sandbox Code Playgroud)

这将永久修改UserForm1(假设您保存工作簿)。如果您想要一个临时用户窗体,则添加一个新的用户窗体,而不是将其设置为UserForm1。完成后,您可以删除表单。

Chip Pearson有一些有关编码VBE的重要信息。


Kev*_*nen 1

我认为代码需要添加到用户窗体中,而不是按钮本身。

所以像

With UserForm1.CodeModule
  'Insert code here
End With
Run Code Online (Sandbox Code Playgroud)

代替你的With ThisWorkbook