Hi,
Hope you can help...
I have the code below which changes the font format of a specific chosen word wherever it appears across the selected range of cells. The target word which requires a format change is determined by the word typed into cell B3. This works fine unless the target word happens to be the first word in the cell, whereupon the code re-formats all the text in the cell and not just the target word. How can I prevent this happening?
Any help greatly appreciated!
Dim cl As Range
Dim SearchText As String
Dim StartPos As Integer
Dim EndPos As Integer
Dim TestPos As Integer
Dim TotalLen As Integer
On Error Resume Next
Application.DisplayAlerts = False
SearchText = Range("B3").Value
On Error GoTo 0
Application.DisplayAlerts = True
If SearchText = "" Then
Exit Sub
Else
For Each cl In Selection
TotalLen = Len(SearchText)
StartPos = InStr(UCase(cl), UCase(SearchText))
TestPos = 0
Do While StartPos > TestPos
With cl.Characters(StartPos, TotalLen).Font
.FontStyle = "Bold"
.ColorIndex = 5
End With
EndPos = StartPos + TotalLen
TestPos = TestPos + EndPos
StartPos = InStr(TestPos, cl, SearchText, vbTextCompare)
Loop
Next cl
End If
Hope you can help...
I have the code below which changes the font format of a specific chosen word wherever it appears across the selected range of cells. The target word which requires a format change is determined by the word typed into cell B3. This works fine unless the target word happens to be the first word in the cell, whereupon the code re-formats all the text in the cell and not just the target word. How can I prevent this happening?
Any help greatly appreciated!
Dim cl As Range
Dim SearchText As String
Dim StartPos As Integer
Dim EndPos As Integer
Dim TestPos As Integer
Dim TotalLen As Integer
On Error Resume Next
Application.DisplayAlerts = False
SearchText = Range("B3").Value
On Error GoTo 0
Application.DisplayAlerts = True
If SearchText = "" Then
Exit Sub
Else
For Each cl In Selection
TotalLen = Len(SearchText)
StartPos = InStr(UCase(cl), UCase(SearchText))
TestPos = 0
Do While StartPos > TestPos
With cl.Characters(StartPos, TotalLen).Font
.FontStyle = "Bold"
.ColorIndex = 5
End With
EndPos = StartPos + TotalLen
TestPos = TestPos + EndPos
StartPos = InStr(TestPos, cl, SearchText, vbTextCompare)
Loop
Next cl
End If