且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-06 12:15:10

用于在运行时添加按钮然后添加事件的代码确实很简单,但很难找到.我可以这么说是因为我在这种困惑上花费了更多的时间,并且比我编写的任何其他程序都更烦躁.

The code for adding a button at runtime and then to add events is truly as simple as it is difficult to find out. I can say that because I have spent more time on this perplexity and got irritated more than in anything else I ever programmed.

创建一个用户表单并输入以下代码:

Create a Userform and put in the following code:

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


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


Now you need to add a Class Module to your code for the project. Please remember it's class module; not Module. And put in the following simple code (in my case the class name is Class2).

Public WithEvents butEvents As MSForms.CommandButton

Private Sub butEvents_click()

    MsgBox "Hi Shrey"

End Sub


就是这样.现在运行它!


That's it. Now run it!