如何将条件格式应用于部分文本字符串的颜色?

时间:2018-08-02 12:08:45

标签: excel vba string conditional-formatting

有没有一种方法可以调整Excel VBA代码以查找和着色找到的文本字符串的特定部分?

我正在使用以下代码查找并突出显示第五列中文本字符串为“ @ gmail.com”和“ @ yahoo.com”的所有单元格。第五列中的文本字符串如下:

  

BBC43555; johnsmith@gmail.com; 77888857778;电话:0018888889

它不能分为几列,因为它可能包含不同数量和顺序的信息字段组合。

我只想突出显示找到的特定文本字符串。我将不胜感激一个简单的解决方案,上面有很好的解释,因为我刚刚开始收集VBA的经验。

Columns("V").Select
Selection.FormatConditions.Add Type:=xlTextString, String:="@gmail.com", _
    TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
    .Color = -16752384
    .TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 13421823
    .TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlTextString, String:="@yahoo.com", _
    TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
    .Color = -16752384
    .TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 13421823
    .TintAndShade = 0
End With

1 个答案:

答案 0 :(得分:1)

以下是第1列中带有文本(无公式)的数据的示例:

Sub test()

Dim CL As Range
Dim POS As Long, Before As Long, After As Long

For Each CL In Sheets(1).UsedRange.Columns(1).Cells
    POS = 0
    If InStr(1, CL.Text, "@gmail.com") > 0 Then POS = InStr(1, CL.Text, "@gmail.com")
    If InStr(1, CL.Text, "@yahoo.com") > 0 Then POS = InStr(1, CL.Text, "@yahoo.com")
    If POS > 0 Then
        Before = InStrRev(CL.Text, ";", POS)
        After = InStr(POS, CL.Text, ";")
        With CL.Characters(Start:=Before + 1, Length:=After - (Before + 1)).Font
            .FontStyle = "Bold"
        End With
    End If
Next CL

End Sub

可能不是最优雅,最防水的解决方案。...

结果:

enter image description here