简体   繁体   中英

Can't add events to dynamically created buttons in VBA userform

Simply put, I've tried following the example found here : How to add events to Controls created at runtime in Excel with VBA but when I click my button nothing happens.

The thing is that I don't create lots of buttons at once, a new button is added everytime the user clicks a certain pre added button.

Code for the button creation :

'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

And the new Class as stated in the example :

Public WithEvents delButton As MSForms.CommandButton

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

I come from python and VBA is extremely confusing.

The most common mistake made when doing this type of thing is forgetting to declare your Class1 instance - or your array/collection of instances - as Global (ie. at the top of the module, not in a Sub or Function).

If you don't do this then your custom class instance goes out of scope and is destroyed as soon as the code creating the button exits.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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