Home » excel » excel – More elegant way of replacing text and formatting it

excel – More elegant way of replacing text and formatting it

Posted by: admin April 23, 2020 Leave a comment

Questions:

Right now I have this:

[M3].select 'Range("M3").Select originally, I like using the [ ] notation
totalrows = [H2].CurrentRegion.Rows.Count
Range("m3:p" & totalrows).Select
[m2].Activate
'Green
    With Application.ReplaceFormat.Interior
        .PatternColorIndex = xlAutomatic
        .Color = 5287936
    End With
    Selection.Replace What:="Green", Replacement:="Red", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=True

Is there a more elegant way of accomplishing this?

I found this today and I love it’s simplicity and have incorporated it in other sections that deal with text replacements.

[M:P].Replace "Green", "Red", xlPart

But, is there an easy way of setting the cell background color to green with a simple statement like that? If the cell contains the text “Green”, change the cell background to Green and don’t change the text.
Thanks for your suggestions!

How to&Answers:

If the cell contains the text "Green", change the cell background to Green and don't change the text.

I’d use this which I think is elegant enough:

[A1].FormatConditions.Add xlExpression, , "=A1=""Green"""
With [A1].FormatConditions(1)
    .Interior.Color = RGB(0, 255, 0)
    .ModifyAppliesToRange [M:P] '~~> of course change this part to suit
End With

Not one liner though.

Answer:

Stumbled upon this one collecting dust and thought a little helper routine would do the trick nicely. ApplyBackgroundColor is nothing fancy — a Select...Case statement with a tiny morsel of error trapping. Here is a link to the colors I used, feel free to build out more functionality: http://dmcritchie.mvps.org/excel/colors.htm

Option Explicit
Public Sub ApplyBackgroundColor(Target As Range, Color As String)
'error trap, if target is empty then exit
If Target Is Nothing Then Exit Sub
With Target
    Select Case UCase(Color)
        Case Is = "GREEN"
            .Interior.ColorIndex = 4
        Case Is = "RED"
            .Interior.ColorIndex = 3
        Case Is = "BLUE"
            .Interior.ColorIndex = 5
        Case Is = "YELLOW"
            .Interior.ColorIndex = 6
        Case Else '<~ don't do anything if the string doesn't match
    End Select
End With
End Sub

And here’s the obligatory test routine to make sure it works:

Sub TestApplyBackgroundColor()

Dim MyRange As Range
Set MyRange = Range(Cells(1, 1), Cells(5, 5))
Call ApplyBackgroundColor(MyRange, "Blue") '<~ not the most elegant, but an improvement

End Sub