如何使用 VBA 将事件添加到在 Excel 中运行时创建的控件中 [英] How to add events to Controls created at runtime in Excel with VBA

查看:24
本文介绍了如何使用 VBA 将事件添加到在 Excel 中运行时创建的控件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add a Control and an associated event at runtime in Excel using VBA but I don't know how to add the events.

我尝试了下面的代码,在我的用户表单中正确创建了 Button,但应显示 hello 消息的关联点击事件不起作用.

I tried the code below and the Button is correctly created in my userform but the associated click event that should display the hello message is not working.

欢迎任何建议/更正.

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

推荐答案

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

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!

这篇关于如何使用 VBA 将事件添加到在 Excel 中运行时创建的控件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆