简体   繁体   English

VBA Excel:在类模块中动态创建的按钮立即运行并且仅运行一次

[英]VBA Excel: dynamically created button in a class module runs immediately and only once

I am trying to make class that would create a button. 我试图使将创建一个按钮的类。 The button should have a macro assigned to it. 该按钮应分配有一个宏。 The macro is a function of the class. 宏是该类的函数。

The code of the class module is the following: 类模块的代码如下:

'Class Module: btnClass
Option Explicit

Dim btn As Button

Function addButton()
    'Adding a button
    Set btn = ActiveSheet.Buttons.Add( _
        Range("A1").Left, _
        Range("A1").Top, _
        Range("A1").Width, _
        Range("A1").Height)
    With btn
        'Assigning a function
        .OnAction = Me.onClickAction
        .Caption = "Button"
    End With
End Function

Function onClickAction()
    MsgBox ("Click")
End Function

The code of the main macro is the following: 主宏的代码如下:

'Module
Option Explicit
Sub main()
    Dim btnInstance As btnClass
    Set btnInstance = New btnClass

    'Calling a function of the instance that creates a button
    Call btnInstance.addButton
End Sub

The code above creates a button successfully. 上面的代码成功创建了一个按钮。 However, the function assigned to the button is run immediately (right after the button is created, not when I click on it), and only once (when you click on the button later, nothing happens). 但是,分配给按钮的功能会立即运行(在创建按钮后立即运行,而不是在我单击按钮时运行),并且仅运行一次(以后单击按钮时什么也不会发生)。

Is there a way in VBA to implement the required functionality using class modules (want to create a class that does not rely on the outside functions)? VBA中是否有一种使用类模块来实现所需功能的方法(想创建一个不依赖外部函数的类)?

To expand on Rory's comment, your class needs something like this: 为了扩展Rory的评论,您的课程需要这样的内容:

Public WithEvents Button As CommandButton

Private Sub Class_Initialize()
    Set Me.Button = Sheet1.OLEObjects("Thebutton").Object
End Sub

Private Sub Button_Click()
    MsgBox "Foo"
End Sub

Then in a normal module create a public instance of the class so it stays in memmory: 然后,在一个普通模块中,创建该类的公共实例,使其保留在内存中:

Public myButt As ButtonClass

Public Sub AddEvent()
    Set myButt = New ButtonClass
End Sub

Note that the click event will only be handled as long as the instance of the class remains in memory. 请注意,只有在类的实例保留在内存中的情况下,才会处理click事件。 If you close the workbook and open it again the event will no longer be handled. 如果您关闭工作簿并再次打开它,将不再处理该事件。

Edit: I forgot to mention, you need to set a reference to Microsoft Forms in order to declare a variable of type CommandButton. 编辑:我忘了提及,您需要设置对Microsoft Forms的引用才能声明CommandButton类型的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM