我想以红色和粗体突出显示我的 Excel 工作表的选定列中的每个单词/短语实例(使用 Excel 2010)。例如,如果列 A1:A10 包含句子“棕狐喜欢另一只棕狐”,我想突出显示此范围内的每个“棕狐”实例。
我在这里找到了一个宏,它仅突出显示每个单元格中的“棕狐”的第一个实例:
Sub colorText()
Dim cl As Range
Dim startPos As Integer
Dim totalLen As Integer
Dim searchText As String
' specify text to searh.
searchText = "brown fox"
' loop trough all cells in selection/range
For Each cl In Selection
totalLen = Len(searchText)
startPos = InStr(cl, searchText)
If startPos > 0 Then
With cl.Characters(startPos, totalLen).Font
.FontStyle = "Bold"
.ColorIndex = 3
End With
End If
Next cl
End Sub
我想编辑这个宏,使它突出显示“棕狐”的每个实例,而不仅仅是第一个。作为尝试,我尝试了以下方法:
Sub colorText()
Dim cl As Range
Dim startPos As Integer
Dim totalLen As Integer
Dim searchText As String
Dim endPos As Integer
Dim testPos As Integer
' specify text to search.
searchText = "brown fox"
' loop trough all cells in selection/range
For Each cl In Selection
totalLen = Len(searchText)
startPos = InStr(cl, searchText)
testPos = 0
Do While startPos > testPos
With cl.Characters(startPos, totalLen).Font
.FontStyle = "Bold"
.ColorIndex = 3
End With
endPos = startPos + totalLen
testPos = testPos + endPos
startPos = InStr(testPos, searchText)
Loop
Next cl
End Sub
但是,这仍然只格式化“brown fox”的第一个实例。
任何想法/编辑将不胜感激。