October 27, 2017

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

3 thoughts on “How to Create Text Boxes on User Form at Runtime

  1. Sir, I’ve a code which creates Checkboxes on userform based on the count given at the beginning. And I’ve followed the above procedure of creating them. Along with the checkboxes textboxes are also created corresponding to the checkboxes, where the user needs to fill data of the checkbox is true. The textboxes when created are disabled, so that it gets enabled only when checkbox is click.
    The issue that I’m facing is, to enable the corresponding textbox when the checkbox is clicked. Also, I can’t get a msgbox if the textbox is left empty when the checkbox is clicked, to force the user to enter data in it. Kindly help me on this issue. I tried the following code:
    (Please note the number of checkboxes to be created is based on the cell value in excel sheet 1 cell a1. The name for the checkbox is given dynamically as CheckBox_1, CheckBox_2 etc based on i)

    Private sub commandbutton1_click
    Dim chkbox as MSForms.checkbox
    Dim count as long
    count = Thisworkbook.sheets(sheet1).cell(1,1)
    Dim i as long
    For i = 1 to count
    Set checkbox.name = “Checkbox_” & i
    If checkbox = true then
    msgbox checkbox & ” selected ”
    Msgbox checkbox & ” not selected”
    End if
    Next i

    End sub

Comments are closed.