November 2, 2017

How to Create Labels at Runtime

How to create labels at runtime automatically on user-form. Last time we learnt how to create text boxes automatically at runtime on user-form. We may also need corresponding labels to make the data entry easier for the user. Watch the video below to learn how to add labels automatically at runtime on user-form:

Watch this video on YouTube.

Here’s the complete VBA code to add labels and text boxes at runtime:

Dim number As Long ‘ global variable

Private Sub UserForm_Initialize()
Dim i As Long
number = InputBox(“Enter no of text-boxes and labels you wish to create at run-time”, “Enter TextBox & Label Number”)
Dim txtB1 As Control
For i = 1 To number
Set txtB1 = Controls.Add(“Forms.TextBox.1”)
With txtB1
.Name = “txtBox” & i
.Height = 20
.Width = 50
.Left = 70
.Top = 20 * i * 1
End With
Next i

Dim lblL1 As Control
For i = 1 To number
Set lblL1 = Controls.Add(“Forms.Label.1”)
With lblL1
.Caption = “Label” & i
.Name = “lbl” & i
.Height = 20
.Width = 50
.Left = 20
.Top = 20 * i * 1
End With
Next i

Dim q As Long
For q = 1 To number
Controls(“lbl” & q) = Cells(1, q)
Next q

End Sub

Private Sub CommandButton1_Click()
Dim p As Long
Dim erow As Long
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

For p = 1 To number

Cells(erow, p) = Controls(“txtBox” & p).Text

Next p

End Sub

Private Sub CommandButton2_Click()
Unload Me
End Sub

Further reading:

Add dynamic Label_Control on the UserForm using VBA

 

 

 

2 thoughts on “How to Create Labels at Runtime

  1. Hello sir,,,
    I coped the code and try to run it, but it didn’t work as well you show in video…
    Some objects doesn’t define as like this:
    Cells(erow, p) = Controls(“txtBox” & p).Text

Comments are closed.