16

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.

3 Answers 3

24

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
    
Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou very much for the feedback. I copy and pasted your code directly into the UserForm2 module, press f5, the form loads, but is still completely blank. I even opened a brand new work book, repeated the above steps, saved the new workbook and press run and still just a blank userform. Is there potentially a setting that i must change or something external to the code, as your code looks like it does exactly what i wanted it to do, but it doesnt :S Thanks again!
OMG! Of Course! Thankyou so much. This is why i love this site. You are a good person!
0

After the end with statement, add:

userform1.show

One more correction:

.top = 10*labelcounter+10

Comments

-4

try below code

Set theLabel = UserForm2.Designer.Controls.Add("Forms.Label.1", "Test1", True)

1 Comment

Use of Designer is lazy and dangerous in this instance. It shows a lack of understanding of the Forms Object and how to interact with them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.