Changing word color to red based on list of words

2019-08-04 12:33发布

I have the following code which allows me to change one word to a different color. Is there a way to change multiple words to different colors so I don't have to set up the macro for 100 different words, and then run the macro 100 different times?

For example - this is the code when searching for word 'dog'. Can I also add in 'cat' somehow?

Sub test()
    Dim changeRange As Range, oneCell As Range
    Dim testStr As String, seekstr As String
    Dim startPosition As String
    seekstr = "dog": Rem adjust

    Set changeRange = ThisWorkbook.Sheets("Sheet1").Range("A2:B21"): Rem adjust

    For Each oneCell In changeRange.Cells
        testStr = CStr(oneCell.Value)
        testStr = LCase(testStr): seekstr = LCase(seekstr): Rem For Case insensitive

        oneCell.Font.ColorIndex = xlAutomatic: Rem remove all colors

        startPosition = 1
        Do While 0 < InStr(startPosition, " " & testStr & " ", " " & seekstr & " ", 1)
            startPosition = InStr(startPosition, " " & testStr & " ", " " & seekstr & " ") + 1
            oneCell.Characters(startPosition - 1, Len(seekstr)).Font.ColorIndex = 3
        Loop

    Next oneCell
End Sub

1条回答
我只想做你的唯一
2楼-- · 2019-08-04 13:17

Work with an array of pets. After getting to each individual cell, cycle through the array, testing each value and adjusting the text color as necessary.

Sub test()
    Dim changeRange As Range, oneCell As Range
    Dim testStr As String, seekstr As String
    Dim startPosition As String
    Dim v As Long, vPETs As Variant

    vPETs = Array("dog", "cat", "hamster")

    Set changeRange = ThisWorkbook.Sheets("Sheet1").Range("A2:B21"): Rem adjust

    For Each oneCell In changeRange.Cells
        testStr = CStr(oneCell.Value)
        testStr = LCase(testStr): seekstr = LCase(seekstr): Rem For Case insensitive

        oneCell.Font.ColorIndex = xlAutomatic: Rem remove all colors

        For v = LBound(vPETs) To UBound(vPETs)
            seekstr = vPETs(v)
            startPosition = 1
            Do While 0 < InStr(startPosition, " " & testStr & " ", " " & seekstr & " ", 1)
                startPosition = InStr(startPosition, " " & testStr & " ", " " & seekstr & " ") + 1
                oneCell.Characters(startPosition - 1, Len(seekstr)).Font.ColorIndex = 3
            Loop
        Next v

    Next oneCell
End Sub
查看更多
登录 后发表回答