Assign on-click VBA function to a dynamically created button on Excel Userform
I'm creating buttons dynamically on an Excel userform with the following code:
With Me.CurrentFrame.Controls.Add("Forms.CommandButton.1")
.Caption = "XYZ"
.name = "AButton"
.Font.Bold = True
.ForeColor = &HFF&
... blah blah blah
End With
I'd like to assign a function to run when these buttons are clicked, but I can't find a straightforward way to do this since there's no property as part of the button itself.
Is there a way to do this using the above idiom? Should I be going about this whole thing in a different way?
To add a control event dynamically in an Excel form; you need to first add the event(s) in a class module. For my example, I am going to add a class module named clsTEST with one event, btn_click()
'#### CLASS NAMED clsTEST
Public WithEvents btn As MSForms.CommandButton
Public frm As UserForm
Dim iCount As Long
Private Sub btn_Click()
iCount = IIf(iCount < 1, 1, iCount + 1)
btn.Caption = "Count " & Str(iCount)
End Sub
'### END CLASS
As you can see, the only thing this will do is set the caption on the button to then number of times you clicked it. Next, in the form code enter the following:
Dim mColButtons As New Collection '## SET A NEW COLLECTION
Private Sub UserForm_Activate()
'
Dim btnEvent As clsTEST
Dim ctl As MSForms.Control
'
Set ctl = Me.Controls.Add("Forms.CommandButton.1")
'
With ctl
.Caption = "XYZ"
.Name = "AButton"
END With
'
Set btnEvent = new clsTEST
Set btnEvent.btn = ctl
set btnEvent.frm = Me
'
mColButtons.add btnEvent
'End Sub
When you activate the form, it will create a button. every time you click on the button the caption will change.
You need to dynamically create code / event handlers for each button.
It take a bit of doing - see here: http://navpadexcel.blogspot.com/2006/11/httpwwwcpearsoncomexcelvbehtm.html
A better way might be to create a bunch of buttons on the form (as many as you think you'll need) ahead of time. Create the event handler code as well. Make them all hidden initially.
Then when your form opens you can dynamically change the button captions, make them visible and move them around. The event code you created initially will be linked to the activated buttons as expected.