Highlight the contents of a control on entry

You probably already know that you can highlight the contents of any textbox by adding two lines of code in its GotFocus event:

Private Sub Text1_GotFocus()    Text1.SelStart = 0     Text1.SelLength = Len(Text1.Text)End Sub

This approach, however, fail shorts when you have dozens of textboxes on your form, and forces you to duplicate the above lines for each and every control. A much better technique is to add a Timer to the form, set its Interval property to a non-zero value (for example, 500 milliseconds is a good choice for this technique) and then add this code to its Timer event procedure:

Private Sub Timer1_Timer()    Static Ctrl As Control    On Error Resume Next    If Not (Ctrl Is ActiveControl) Then        Set Ctrl = ActiveControl        ' If the new control isn't a TextBox or a ComboBox, the        ' following two statements are ignored        Ctrl.SelStart = 0        Ctrl.SelLength = Len(Ctrl.Text)    End If       End Sub

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: