Developer

VB6 Tip: Selecting all text when a Text Box gets the focus

In many applications, especially forms, it is often desirable to have all of a control's text selected when it receives focus. This Visual Basic tip shows you how that is accomplished.

This article originally appeared in the Builder.com Visual Basic e-newsletter. Click here to subscribe automatically.

When the focus moves to a Text Box that contains text, Visual Basic 6's default is to position the caret (editing cursor) at the start of the text. In some applications, it might be more appropriate to have all of the control's text selected when it receives the focus. One advantage to this is that it will delete the existing text if the user starts typing something new. This tip shows you how to implement this behavior.


Related resources

Launch and terminate applications in Visual Basic 6.0
Download: QuickStart: Visual Basic .NET
Context! VB


A Text Box has two properties that determine what text, if any, is selected:

  • SelStart specifies the character position where the selection starts.
  • SelLength specifies the length of the selection, in characters.

You can select all text in a Text Box by setting SelStart to 0 and SelLength to the length of the text. Here's a short procedure that does this:

Sub SelectAllText(tb As TextBox)

tb.SelStart = 0
tb.SelLength = Len(tb.Text)

End Sub

Then, for each Text Box that you want to behave this way, call the procedure from the GotFocus event procedure, passing the name of the Text Box as the argument:

Private Sub Text1_GotFocus()

SelectAllText Text1

End Sub

This works when the Text Box gets the focus either by tabbing or by a mouse click.

Peter Aitken has been programming with Visual Basic since Version 1.0. He has written numerous books and magazine articles on Visual Basic and other computer and programming topics.

Editor's Picks

Free Newsletters, In your Inbox