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.

braX
  • 11,506
  • 5
  • 20
  • 33
BiGXERO
  • 7,104
  • 8
  • 23
  • 25

3 Answers3

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
    
brettdj
  • 54,857
  • 16
  • 114
  • 177
  • 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! – BiGXERO May 11 '12 at 03:57
  • 1
    OMG! Of Course! Thankyou so much. This is why i love this site. You are a good person! – BiGXERO May 11 '12 at 04:34
0

After the end with statement, add:

userform1.show

One more correction:

.top = 10*labelcounter+10
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
-4

try below code

Set theLabel = UserForm2.Designer.Controls.Add("Forms.Label.1", "Test1", True)
chriz
  • 1,339
  • 2
  • 16
  • 32