How to apply conditional formatting to color parti

2019-09-23 02:08发布

问题:

Is there a way to adjust the Excel VBA code to find and color a specific part of the text string found?

I am using the following code to find and highlight all cells with text string "@gmail.com" and "@yahoo.com" in column V. The text string in column V is like this:

BBC43555;johnsmith@gmail.com;77888857778;phone:0018888889

It cannot be divided into columns because it may contain different number and order of information fields combined in it.

I would like to highlight only the specific text string found. I would appreciate a simple solution with a good explanation, since I am just starting to collect experience with 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:

Here is an example on data in column 1, with text (no formulas):

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

Maybe not the most elegant and waterproof solution....

Outcome: