Click for Button Added at RunTime

L

LRL

I'm adding a button to a userform at runtime using the following code:


Private Sub UserForm_Activate()

Dim Mycmd As Control

Set Mycmd = Controls.Add("Forms.CommandButton.1", "CommandButton2",
Visible)
Mycmd.Left = 12
Mycmd.Top = 90
Mycmd.Width = 125
Mycmd.Height = 20
Mycmd.Caption = "unassigned"

End Sub

Private Sub CommandButton2_Click()

Dim i As Integer
i = 1

End Sub

I set a breakpoint in the CommandButton2_Click routine to see if
clicking actually works but the breakpoint is never hit.

How do I capture the click events for the button I add at runtime?

Thanks!
 
J

JE McGimpsey

LRL said:
I'm adding a button to a userform at runtime using the following code:

You need to declare your object as a Form-level WithEvents object. I'd
also suggest creating the button in the userform's Initialize event,
rather than the Activate event:

Public WithEvents btnMyCmd As MSForms.CommandButton

Private Sub UserForm_Initialize()
Set btnMyCmd = Me.Controls.Add( _
"Forms.CommandButton.1", _
Name:="CommandButton2", _
Visible:=True)
With btnMyCmd
.Left = 12
.Top = 90
.Width = 125
.Height = 20
.Caption = "Unassigned"
End With
End Sub

Private Sub btnMyCmd_Click()
MsgBox "You clicked my button!"
End Sub

The variable must be declared at the Form/module level in order to work
when the form is shown.

Note that if you have multiple buttons, or buttons on multiple forms
that will do similar actions, you could create a button class and create
the buttons as members of that class.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top