Assign a macro to a dynamically created button

Assign a macro to a dynamically created button

Anonymous
Not applicable
2,247 Views
2 Replies
Message 1 of 3

Assign a macro to a dynamically created button

Anonymous
Not applicable

Hello, 

in my Autocad VBA code, I'm creating a series of dynamic buttons. But by simplifying the case, let's see a simple case :

 

Dim myCustomControl  As Control

Set myCustomControl = UserForm1.Controls.Add("Forms.CommandButton.1", "MyButton", True)

With myCustomControl
      .Caption = "myTextButton"
      .Left = 0
      .Width = 50
      .top = 0
End With

 

I need to associate a macro to this button. I tried to define the sub:

 

Private Sub MyButton_Click()

msgBox ("hello!")

End Sub

 

But when I click on the button the sub is not called 🤔 .

 

1) Is there something different to be done?

2) Can I give a generic name to the associated macro (not "MyButton_Click()"  by also passing generic parameters MyMacro(par1 par2)?

 

Thank you,

 

Giuseppe

0 Likes
Accepted solutions (1)
2,248 Views
2 Replies
Replies (2)
Message 2 of 3

norman.yuan
Mentor
Mentor
Accepted solution

When you adds control object to userform in VBA/Classical VB(4/5/6), the control is declared as "WithEvents..." behind scene, so the the code window's top-left drop-down list, you can choose that control and then in the code window's top-right drop-down list you would see a list of available events for that control and choose one to handle.

 

Now that you add a control to the form with code (at runtime/dynamically), your code must declare the control as "WithEvents ..." to so that you can handle desired event(s) of that control. You would notice, once you declare a control (or whatever Object that comes with events) , that control/Object would be available in the code window's top-left drop-down list and its available events listed on code window's top-right drop-down list for you to choose to handle.

 

Following picture shows the code window of the most simple scenario of adding a button to UserForm (hope the code is readable/clear enough in the picture):

Dynamic control event handling in VBA.png

 

HTH

 

 

Norman Yuan

Drive CAD With Code

EESignature

Message 3 of 3

Anonymous
Not applicable

Thank you Norman,

it works as expected 🙂,

 

Giuseppe

0 Likes