Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Adding Labels to User Form = Blank UserForm

Tags:

excel

vba

I'm trying to dynamically add buttons to the userform, but the userform just comes up blank. Ive simplified the essence of the code as much as possible for error checking (not that it's helped me)

Sub addLabel()
UserForm2.Show    
Dim theLabel As Label
Dim labelCounter As Integer

For labelCounter = 1 To 3
    Set Label = UserForm2.Controls.Add("Forms.Label.1", "Test" & labelCounter, True)
    With theLabel
        .Caption = "Test" & labelCounter
        .Left = 10
        .Width = 50
        .Top = 10
    End With
End Sub

Is there any way of checking if the buttons have been added but are invisible? Or why they are not being added. Any help greatly appreciated.

like image 365
BiGXERO Avatar asked May 11 '12 02:05

BiGXERO


People also ask

How do I add a label to a UserForm?

A Label is the control that you use to add text to a UserForm. Click the UserForm and look to the Toolbox (go to View > Toolbox if you don't see it). Click the A in the toolbox. Once you click the A, go to the form and click and drag until a label appears.

How do I create a fillable form in Excel using VBA?

Step 1 − Navigate to VBA Window by pressing Alt+F11 and Navigate to "Insert" Menu and select "User Form". Upon selecting, the user form is displayed as shown in the following screenshot. Step 2 − Design the forms using the given controls. Step 3 − After adding each control, the controls have to be named.


1 Answers

A few things:

  1. You need to show your UserForm as vbModeless - else the code stops on UserForm2.Show
  2. You are creating an object called Label then using With on theLabel
  3. You will then need to increment the position of your three labels to avoid overlap (which I have done using Top).

    Sub addLabel()
    UserForm2.Show vbModeless
    Dim theLabel As Object
    Dim labelCounter As Long
    
    For labelCounter = 1 To 3
        Set theLabel = UserForm2.Controls.Add("Forms.Label.1", "Test" & labelCounter, True)
        With theLabel
            .Caption = "Test" & labelCounter
            .Left = 10
            .Width = 50
            .Top = 10 * labelCounter
        End With
    Next
    End Sub
    
like image 116
brettdj Avatar answered Oct 02 '22 09:10

brettdj