Right now I have this:
[M3].select \'Range(\"M3\").Select originally, I like using the [ ] notation
totalrows = [H2].CurrentRegion.Rows.Count
Range(\"m3:p\"
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
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.