The Problem (Q-score 5, ranked #71st of 95 in the VBA Core archive)
The scenario as originally posted in 2009
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?
Why community consensus is tight on this one
Across 95 VBA Core entries in the archive, the accepted answer here holds niche answer (below median) status — meaning voters are unusually aligned on the right fix.
The Verified Solution — niche answer (below median) (+7)
Advisory answer — community consensus with reference links
Note: the verified answer below is a reference / advisory response rather than a copy-ready snippet.
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.
Loop-performance notes specific to this pattern
The loop in the answer iterates in process. On a 2026 Office build, setting Application.ScreenUpdating = False and Application.Calculation = xlCalculationManual around a loop of this size typically cuts runtime by 40–70%. Re-enable both in the Exit handler.
When to Use It — vintage (14+ years old, pre-2013)
Ranked #71st in its category — specialized fit
This pattern sits in the 94% tail relative to the top answer. Reach for it when your scenario closely matches the question title; otherwise browse the VBA Core archive for a higher-consensus alternative.
What changed between 2009 and 2026
The answer is 17 years old. The VBA Core object model has been stable across Office 2013, 2016, 2019, 2021, 365, and 2024/2026 LTSC, so the pattern still compiles. Changes that might affect you: 64-bit API declarations (use PtrSafe), blocked macros in downloaded files (Mark-of-the-Web), and the shift toward Office Scripts for web-first workflows.