2015-09-04 40 views
0

我一直在使用下面,但发现它只突出显示/更改每个单元格的第一个子字符串的字体颜色。我如何确保它也突出显示后续的内容?如何突出显示单元格中特定子字符串的所有出现次数?

Sub test4String2color() 
    Dim strTest As String 
    Dim strLen As Integer 
    strTest = Range("F1") 
    strLen = Len(strTest) 
    For Each cell In Range("A1:D100") 
     If InStr(cell, strTest) > 0 Then 
     cell.Characters(InStr(cell, strTest), strLen).Font.Color = vbRed 
    End If 
    Next 
End Sub 

回答

0

你只需要遍历字符串,直到你无法找到strTest了。使用前一个查找的位置开始连续搜索。

Sub test4String2color() 
    Dim strTest As String, cell As Range 
    Dim strLen As Long, p As Long 

    With ActiveSheet 
     strTest = .Range("F1") 
     strLen = Len(strTest) 
     For Each cell In Intersect(.Range("A1:D100"), .UsedRange) 
      p = InStr(1, cell, strTest) 
      Do While CBool(p) 
       cell.Characters(p, strLen).Font.Color = vbRed 
       p = InStr(p + 1, cell, strTest) 
      Loop 
     Next 
    End With 
End Sub 
相关问题