Highlight the contents of a control on entry

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

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist