Reputation: 171
I have a userform that dynamically places a commandButton
onto the user form but I can't seem to get the dynamic event handler set up properly: Below shows the code for how I have set up the dynamic button:
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
I have also defined dim WithEvents cButton as Commandbutton
outside of any sub or procedure and then finally I have the event handler for the dynamic button, which I simply want to output a message for now:
Private Sub cButton_Click()
MsgBox "Dynamic Handler functioning correctly"
End Sub
Now that I am able to create event handlers for dynamic events for individual controls, however I am creating multiple controls and they all have the same name cButton
so how would I be able to create individual event handlers for each of them. Below shows the code that is used to create the multiple controls:
If TextBox1 <> vbNullString Then
For i = 1 To TextBox1.Value
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
Next i
End IF
Upvotes: 2
Views: 1330
Reputation: 1561
cButton
should only be declared once:
Dim WithEvents cButton As CommandButton
Sub UserForm_Initialize()
Set cButton = Me.Controls.Add("Forms.CommandButton.1")
With cButton
.Left = 150
.Top = 0
.Width = 300
.Height = 140
End With
End Sub
Private Sub cButton_Click()
MsgBox "Dynamic Handler functioning correctly"
End Sub
Upvotes: 3