Search code examples
vbaexcelloopstextboxcontrols

Initializing all textboxes with a for loop


I have an Initialization for a userform. It works fine when I initialize using the commented out part of the code, but when I use the code as shown below, I get a runtime error 91.

I need a way to loop through or select all textboxes to give them default value, color and etc...

Private Sub UserForm_Initialize()
Dim i As Long
Dim ctl As Control
For i = 1 To 4
    ctl = "TextBox" & i
    ctl.Value = ""
Next i
'TextBox1.Value = ""
'TextBox2.Value = ""
'TextBox3.Value = ""
'TextBox4.Value = ""
End Sub

Solution

  • In general, to refer to a TextBox of the form, you need Controls("TextboxN). If you want to loop, it is like this - Me.Controls("Textbox" & i), in case that you have not deleted any textboxes and they are following the default order Thus, this is a possibility:

    Private Sub UserForm_Initialize()
    
        Dim i As Long
        Dim ctl As Control
        For i = 1 To 4
            Me.Controls("Textbox" & i) = i
            Me.Controls("Textbox" & i).BackColor = vbGreen
        Next i
    
        Debug.Print Me.TextBox3.Value
    
    End Sub
    

    With this screenshot, showing each TextBox getting a value of 1,2,3 or 4 and a green color:

    enter image description here

    Or even this, if you want to make the outlook of the controls a bit different:

    Private Sub UserForm_Initialize()
    
        Dim i       As Long
        Dim ctl     As Control
    
        For i = 1 To 4
            With Me.Controls("Textbox" & i)
                .Value = i
                If i Mod 2 = 0 Then
                    .BackColor = vbBlue
                    .ForeColor = vbWhite
                Else
                    .BackColor = vbGreen
                    .BackColor = vbRed
                End If
            End With
        Next i
    
    End Sub
    

    enter image description here

    If you are naming the textboxes, following your own programming logic, then looping through the collection of controls and checking the TypeName of the control is a better solution.