I am struggling to figure out an elegant way to apply conditional formatting rules via VBA. I prefer VBA because a) the rules will apply to multiple worksheets, and b) it prevents the CF duplication problem when copying/pasting between worksheets.
I have a list of inventory items, all kept in different locations. I want to format based on location with the following formatting:
Font color (will change for each location); Top border (same color as font); Bottom border (same color as font)
Also, the range needs to be dynamic in that for each worksheet, it applies to the table on that sheet. I would like to apply the same code to each applicable worksheet, rather than needing to hard-code the table name for each worksheet.
Any help would be greatly appreciated.
--UPDATE--
I tried to adapt J_V's code here but receive a "Run-time error '5': Invalid procedure call or argument" on the Public Sub's r.FormatConditions.Add Type:=xlExpression, Formula1:=formula
. I'm unsure if the last bit on borders is correct since the run-time stops the macro. I also still need to work in dynamic table references, but I'm working one issue at a time.
Sub ConditionalFormatting()
Dim myRange As Range
Set myRange = ThisWorkbook.Sheets("Widget1").Range("Widget1_table[Location]")
myRange.FormatConditions.Delete
Call FormatRange(myRange, 10, "=$E5="Warehouse1")
Call FormatRange(myRange, 11, "=$E5="Warehouse2")
Call FormatRange(myRange, 13, "=$E5="Warehouse3")
End Sub
Public Sub FormatRange(r As Range, color As Integer, formula As String)
r.FormatConditions.Add Type:=xlExpression, Formula1:=formula
r.FormatConditions(r.FormatConditions.Count).Font.colorindex = color
With r.FormatConditions(1).Borders(xlTop)
.LineStyle = xlContinuous
.Color = color
.TintAndShade = 0
.Weight = xlThin
End With
With r.FormatConditions(1).Borders(xlBottom)
.LineStyle = xlContinuous
.Color = color
.TintAndShade = 0
.Weight = xlThin
End With
r.FormatConditions(1).StopIfTrue = False
End Sub