Hi everyone,
New user, and novice when it comes to vba. What I'm trying to do is change the text color of specific keywords in a spreadsheet. For example, I'd like to highlight the text of 'how to' in the following sentence "I want to know how to change text color", so that it looks like this "I want to know how to change text color".
I came across the following, and it works for only two terms (example, "how to" , "how do I"), but I have a string of about 15 terms I'd like to use, but anything I change over two, I get the subscript out of range error. Any help would be much appreciated! Thanks!
Option Explicit
Option Compare Text
Sub test()
Dim myList, myColor, myPtn As String, r As Range, m As Object, x
Columns(1).Font.ColorIndex = xlAutomatic
myList = VBA.Array("Cat", "Mouse") '<-- add more if needed
myColor = VBA.Array(vbRed, vbBlue) '<-- adjust as per myList(use Color value, not ColorIndex)
myPtn = Join$(myList, Chr(2))
With CreateObject("VBScript.RegExp")
.Global = True
.IgnoreCase = True
.Pattern = "([\^\$\(\)\[\]\*\+\-\?\.\|])"
myPtn = Replace(.Replace(myPtn, "\$1"), Chr(2), "|")
.Pattern = "\b(" & myPtn & ")\b"
For Each r In Range("a1", Range("a" & Rows.Count).End(xlUp))
If .test(r.Value) Then
For Each m In .Execute(r.Value)
x = Application.Match(m, myList)
If Not IsError(x) Then
r.Characters(m.firstindex + 1, m.Length).Font.Color = myColor(x - 1)
End If
Next
End If
Next
End With
End Sub
Bookmarks