Searching for text within string and changing colour of found text

rjf298

New Member
Joined
Sep 9, 2009
Messages
3
Hi there - I have some code that allows me to search for pre-defined text (eg. house) in a range and then format the resultant text in the string (coloured red).

What I want to know is how to change the code so that rather than searching for set text it searches for whatever text is contained within a certain cell (ie. user-defined)?

The code I have is:

Sub HighLight()
Dim WS As Worksheet, c As Range
Dim FindWord As String
Dim MyStart As Long, MyLenght As Long

FindWord = "house"

For Each WS In Worksheets
With WS.Cells
Set c = .Find(FindWord, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
MyStart = InStr(c.Value, FindWord)
MyLength = Len(FindWord)
With c.Characters(Start:=MyStart, Length:=MyLength).Font
.Size = 10
.Color = -16776961
End With
Set c = .FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End With
Next

End Sub
 

Excel Facts

Formula for Yesterday
Name Manager, New Name. Yesterday =TODAY()-1. OK. Then, use =YESTERDAY in any cell. Tomorrow could be =TODAY()+1.
Thanks very much for that.

Im new to VBA so am adapting a colleagues code - is there any reason why when entering a search term of x characters, the code only highlights the first x characters of the cell it has found my search term in, and not the actual word itself?!

Thanks
 
Upvote 0

Forum statistics

Threads
1,224,523
Messages
6,179,301
Members
452,904
Latest member
CodeMasterX

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top