无法将事件添加到VBA userform中dynamic创build的button

简单地说,我试着按照这里find的例子: 如何将事件添加到在Excel中使用VBA在运行时创build的控件,但是当我单击我的button时,什么也没有发生。

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

代码为button创build:

'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实例(或者你的数组/实例集合)声明为Global(即在模块的顶部,而不是在Sub或Function中)。

如果你不这样做,那么你的自定义类实例超出了范围,并且只要创buildbutton的代码退出就被销毁。

 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