A simple example:
TextBox1 with the text "Hello My World" and a button looking for the word "My"
Code:
Option Explicit
Private Sub UserForm_Initialize()
TextBox1.Text = "Hello My World"
End Sub
Private Sub CommandButton1_Click()
Dim strSearch As String
strSearch = "My"
With TextBox1
If InStr(.Text, strSearch) Then
.SelStart = InStr(.Text, strSearch) - 1
.SelLength = Len(strSearch)
.SetFocus
End If
End With
End Sub
I got this to work below. I used 2 textboxes on a form and a button. It works when it finds what i searched for. But if I search for something that is not there, it highlights everything in the textbox. How do I not highlight everything when not found?
Private Sub Command2_Click()
Dim strSearch As String
strSearch = Me.Text0.Value
Me.Text3.SetFocus
With Me.Text3
If InStr(.Text, strSearch) Then
.SelStart = InStr(.Text, strSearch) - 1
.SelLength = Len(strSearch)
.SetFocus
End If
End With
Private Sub Command2_Click()
Dim strSearch As String
strSearch = Me.Text0.Value
With Me.Text3
If InStr(.Text, strSearch) Then
.SelStart = InStr(.Text, strSearch) - 1
.SelLength = Len(strSearch)[blue]
Else
.SelStart = 0
.SelLength = 0
End If[/blue]
.SetFocus
End With
End Sub
It may be by default the text in a textbox gets highlighted when the text box gets focus...
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.