Dynamic Label and Textbox during runtime in excel vba

Excel VBA allows us to add the user forms with various controls. In userform we can insert Labels and Textboxes while designing. In this post you can learn how to create the label and text box dynamically during the runtime with the help of command button.

Add a userform in the vba and insert a command box. You can give proper name to command box.

Add below code to the command box. this procedure is called when the command button is triggered while the userform is running. However the variable i should be declared as module level variable to retain the value for the next trigger.

Dim i As Integer ' this make the variable not procedure specific.

Private Sub CommandButton1_Click()

i = i + 1

Dim txtbx As Object
Dim txtlbl As Object

Set txtlbl = UserForm2.Controls.Add("Forms.Label.1")

With txtlbl
.Caption = "Label" & i
.Top = i * 20
.Left = 10
End With

Set lblbx = UserForm2.Controls.Add("Forms.TextBox.1")

With lblbx
.Top = i * 20
.Left = 50
End With

End Sub

When you click on command button it will add one label and one text box in the userform during the runtime.

Leave a Comment