Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding controls to a frame in an Excel userform with VBA

I need to create labels and buttons dynamically and then add them to a frame within a userform. How do I do this? Seems like it should be easier than it really is.

like image 830
notnot Avatar asked Feb 19 '09 04:02

notnot


People also ask

How do I add controls to a UserForm?

Controls are added in the UserForm from the Toolbox, in the Visual Basic Editor. Select the control in the ToolBox and drag to the form to add it. Another method is to left-click on the control in the ToolBox, go to the form and left-click again, and the control will be added.

What type of controls can you add to a VBA form?

Examples of common controls include list boxes, option buttons, and command buttons. Controls can also run assigned macros and respond to events, such as mouse clicks, by running Visual Basic for Applications (VBA) code.

How do you use controls in VBA?

VBA Option ButtonsStep 1: Go to the Developer tab and click on the insert button. Step 2: Choose the option button icon from the drop-down list and make sure the button you choose is under the ActiveX controls. Step 3: Draw the button on the sheet as per the user's convenience.


1 Answers

The following code demonstrates how you can dynamically populate a frame in a userform with controls...

In the form I used I had a frame control named Frame1, so in the UserForm_Initialize you call Frame1.Controls.Add to embed a control in the frame. You can set the control which gets returned to a WithEvents control variable that you have defined in the UserForm code module so you can respond to events on whatever controls you want...

So with this method you need to pre-write any event code you want for any controls you create...

Also note that you can position and size your controls even if the top, left, width, and height properties don't necessarily come up in intellisense...

Private WithEvents Cmd As MSForms.CommandButton
Private WithEvents Lbl As MSForms.Label

Private Sub UserForm_Initialize()
    Set Lbl = Frame1.Controls.Add("Forms.Label.1", "lbl1")
    Lbl.Caption = "Foo"
    Set Cmd = Frame1.Controls.Add("Forms.CommandButton.1", "cmd1")
End Sub

Private Sub Cmd_Click()
    Cmd.Top = Cmd.Top + 5
End Sub

Private Sub Lbl_Click()
    Lbl.Top = Lbl.Top + 5
End Sub
like image 50
Jon Fournier Avatar answered Oct 15 '22 17:10

Jon Fournier