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

 

 

 

Published by

Dinesh Kumar Takyar

Welcome to exceltrainingvideos.com! My aim is to help you learn MS Excel including VBA. I always felt that a good way to learn something was to find solutions to problems in that domain. That is why I share these Excel videos with you. Mostly these are questions asked during my corporate training sessions. I've been training individuals and companies in computers since 1991. I did my B. Sc. (Vordiplom), M. Sc. (Diplom) and Ph.D. (Dr. rer. nat.) from Hamburg, Germany. The best thing about solving some of my visitor's questions is that I also gain new insights. For more Excel VBA solutions you may like to visit my YouTube channel: http://youtube.com/familycomputerclub For a structured Excel VBA training course online you can visit: https://www.youtube.com/excelvbaonline

One thought on “How to Create Labels at Runtime”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.