How to apply conditional formatting to color partial text string?

别说谁变了你拦得住时间么 提交于 2019-12-25 18:55:33

问题


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:



来源:https://stackoverflow.com/questions/51653276/how-to-apply-conditional-formatting-to-color-partial-text-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!