Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Search and Highlight found word/phrase

Status
Not open for further replies.

abenitez77

IS-IT--Management
Oct 18, 2007
147
US
How can I search for something in a textbox and when found, highlight the word or phrase searched. I don't want the whole textbox highlighted.

thanks,

alex
 
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

Have fun.

---- Andy
 
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

End Sub
 
Try:

Code:
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...

Have fun.

---- Andy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top