vba - 无法将事件添加到 VBA 用户窗体中动态创建的按钮

标签 vba excel

简而言之,我尝试按照此处找到的示例进行操作: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 非常困惑。

最佳答案

做这类事情时最常见的错误是忘记将您的 Class1 实例 - 或实例的数组/集合 - 声明为全局(即在模块的顶部,而不是在子或函数中)。

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

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

关于vba - 无法将事件添加到 VBA 用户窗体中动态创建的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125209/

相关文章:

excel - 从变量命名工作表

excel - 找到文本vba时代码不返回值

vba - PasteSpecial(运行时错误 1004)

c# - 如何禁用从excel复制图片

vba - 有趣的符号#

vba - 如何浏览工作表的所有公式和数组公式而不多次重复每个数组公式?

excel - VBA:从剪贴板粘贴不可靠

vba - Excel 粘贴到可见、转置为链接组合功能

c# - 在 .Net 中的 Excel 文档中查找最右边的单元格

vba - 使用 Excel 2013 隐藏行