如何在Excel 2010中突出显示给定范围或选择的同一单元格中单词的每个实例?

时间:2013-03-15 17:35:46

标签: excel vba format

我想在Excel工作表的选定列(使用Excel 2010)中以红色和粗体突出显示单词/短语的每个实例。例如,如果列A1:A10包含句子“棕色狐狸喜欢其他棕色狐狸”,我想在此范围内突出显示“棕色狐狸”的每个实例。

我找到了一个宏here,它只突出显示每个单元格中第一个“棕色狐狸”:

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

然而,这仍然只是格式化“棕色狐狸”的第一个实例。

非常感谢任何想法/编辑。

2 个答案:

答案 0 :(得分:4)

你的错误是你的逻辑。您应该更正以下代码:

 startPos = InStr(testPos, cl, searchText, vbTextCompare)

而不是这样做:

 startPos = InStr(testPos, searchText)

在第二个子目录中。你现在看到了吗? :-)

答案 1 :(得分:0)

当我想要在一系列单元格中格式化特定单词时,我遇到了同样的问题。经过多次尝试和大量的互联网搜索,这是最好的......

Sub FormatWords()
Dim Rng As Range, cl As Range, Red As Integer
Dim oStrg As String
Set Rng = Range(Range("D1"), Range("D" & Rows.Count).End(xlUp))
On Error Resume Next
oStrg = "Apple"
If oStrg = "" Then Exit Sub

For Each cl In Rng
    Red = InStr(1, cl, oStrg, vbTextCompare)

    Do Until Red = 0
        With cl.Characters(Red, Len(oStrg))
        .Font.Color = RGB(230, 25, 55)
        .Font.Bold = True
         End With
         Red = InStr(Red + 1, cl, oStrg, vbTextCompare)
    Loop
Next cl

oStrg = "Mango"
If oStrg = "" Then Exit Sub

For Each cl In Rng
    Orange = InStr(1, cl, oStrg, vbTextCompare)
    Do Until Orange = 0
        With cl.Characters(Orange, Len(oStrg))
        .Font.Color = RGB(250, 200, 0)
        .Font.Bold = True
        End With

        Orange = InStr(Orange + 1, cl, oStrg, vbTextCompare)
    Loop
Next cl

End Sub