无法在VBA用户表单中向动态创建的按钮添加事件

时间:2017-09-08 22:18:14

标签: excel vba excel-vba

简单地说,我已经尝试过按照此处找到的示例:How to add events to Controls created at runtime in Excel with VBA但是当我点击我的按钮时没有任何反应。

问题是我不能一次创建大量按钮,每次用户点击某个预先添加的按钮时都会添加一个新按钮。

创建按钮的代码:

'Finally the delete button
Dim newb As MSForms.CommandButton
'thisQuant is a var keeping track of how many buttons there are
Set newb = FProducts.Controls.Add("Forms.CommandButton.1", "del" & thisQuant, False)
Dim Button As New Class1
Set Button.delButton = newb

示例中所述的新类:

Public WithEvents delButton As MSForms.CommandButton

Private Sub delButton_Click()
    MsgBox "test"
    'quantProd = CInt(NewNota.ProductQuant.Caption)
End Sub

我来自python,VBA非常混乱。

1 个答案:

答案 0 :(得分:4)

执行此类操作时最常犯的错误是忘记将Class1实例 - 或您的数组/实例集合 - 声明为Global(即在模块的顶部,而不是在Sub或Function中)。

如果不这样做,那么您的自定义类实例将超出范围,并在创建按钮的代码退出后立即销毁。

Dim Button As Class1

Sub CreateButton()
    Dim newb As MSForms.CommandButton

    '...

    'thisQuant is a var keeping track of how many buttons there are
    Set newb = FProducts.Controls.Add("Forms.CommandButton.1", "del" & thisQuant, False)

    Set Button = New Class1
    Set Button.delButton = newb

    '...

End Sub