Search code examples
vbatextboxdisabled-input

How to disable text box until previous textbox has been populated?


I have a userform which is made up of a single combobox followed by multiple text boxes.

How would I disable and grey out each textbox, preventing any user input unless the textbox above it has been populated?

I tried both of these techniques.

Me.CSockett.Enabled = Not IsNull(Me.CSocketl)

'If CSocketl.Value = "" Then
'    Me.CSockett.Enabled = False
'    Else
'    Me.CSockett.Enabled = True
'End If

Solution

  • I created a new UserForm with 2 TextBox all with default names. You can apply this concept to each textbox you need to.

    Private Sub TextBox1_Change()
    
    If Not Me.TextBox1.Text = "" Then
        Me.TextBox2.Enabled = True
        Me.TextBox2.BackColor = &H80000005
    Else
        Me.TextBox2.Enabled = False
        Me.TextBox2.BackColor = &H80000016
    End If
    
    End Sub
    
    Private Sub UserForm_Initialize()
    
    Me.TextBox2.Enabled = False
    Me.TextBox2.BackColor = &H80000016
    
    End Sub
    
    

    The Initialize code disables the 2nd textbox and sets the background colour (see below) to visually show it's disabled when the form first opens.

    The Change code evaluates on each change to the TextBox.Text property if the next textbox should be enabled or not.

    Note: With a bit of searching you will find a million other ways to check for an empty textbox other than ...Text = "".

    UserForm when first opened (Initialize Code):

    Initialized userform with no input to textbox1

    After typing a character into textbox1:

    Form after entering "A" into textbox1 showing textbox2 is now enabled

    The .Enabled property if set to False will not let the user click or tab to the Control (in this case, the TextBox). I add the BackColor change to have a visual aide showing the user it's 'greyed out' - otherwise it looks the same as an enabled textbox and can cause frustration to the user.

    Naturally, the colour is set back to the default value once enabled.