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