How to Create Text Boxes on User Form at Runtime

How to create text boxes on User Form at runtime, access the created text boxes, enter data into them and transfer the data to the worksheet. There are many complicated ways of doing this but we describe below an elegant and easy method. Watch the video:

 

Watch this video on YouTube.

Here’s the complete VBA code:

Dim number As Long
Private Sub UserForm_Initialize()
Dim i As Long
number = InputBox(“Enter no of text-boxes you wish to create at run-time”, “Enter TextBox 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 = 150
.Left = 20
.Top = 20 * i * 1
End With
Next i
End Sub

Private Sub CommandButton1_Click()
Dim p As Long
For p = 1 To number
Cells(1, p) = Controls(“txtBox” & p).Text
‘Cells(p, 1) = Controls(“txtBox” & p).Text
Next p
End Sub

Private Sub CommandButton2_Click()
Unload Me
End Sub

Further reading:

How to create textboxes during runtime, and name them