Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

excel - How to apply conditional formatting to color partial text string?

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;[email protected];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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...