Selecting TextBox Text

TextBoxes have a property called EnterFieldBehavior which allows you to control how the text is selected when a user enters the control. A setting of zero selects all the text in the TextBox on entry and a setting of one selects the text (and/or cursor location) that was selected when the TextBox was last exited.

Selecttext1

You can use the TextBox’s Enter event to customize how the text is selected. The SelStart and SelLength properties can be used to select text in any fashion you want.

In this example, there are two TextBoxes on the userform. The first TextBox holds a date and the second holds a path to a file. In TextBox1_Enter, the code compares the date in the TextBox to the current date. If it’s the same month, only the day is selected. If it’s a different month, both the month and the day are selected.

In TextBox2_Enter, the code uses InstrRev to find the last “” in the string. If one is found, only the file name is selected.

Private Sub TextBox1_Enter()

    If IsDate(Me.TextBox1.Text) Then
        If Month(Now) = Month(Me.TextBox1.Text) Then
            Me.TextBox1.SelStart = 3
            Me.TextBox1.SelLength = 2
        Else
            Me.TextBox1.SelStart = 0
            Me.TextBox1.SelLength = 5
        End If
    End If
    
End Sub

Private Sub TextBox2_Enter()

    Dim lLastSlash As Long
    
    lLastSlash = InStrRev(Me.TextBox2.Text, “”)
    
    If lLastSlash > 0 Then
        Me.TextBox2.SelStart = lLastSlash
        Me.TextBox2.SelLength = Len(Me.TextBox2.Text)
    End If
    
End Sub

All this selecting is to make it easier for the user to change the appropriate text. If you’re going to use custom selecting in the Enter event, be sure you set the EnterFieldBehavior to 1. A setting of zero in this property will override any event code you have. Here’s the form in action:

Selecttext2

Posted in Uncategorized


Posting code? Use <pre> tags for VBA and <code> tags for inline.

Leave a Reply

Your email address will not be published.