Conditional Formatting Macro

FredMcStaire

New Member
Joined
Jan 19, 2009
Messages
24
Hopefully a simple one:
I have a particular conditional formatting style I use for my error checking formulas. When the formula in the cell = 0, then one style appears and when the value <>0, then another format appears.

I'm struggling to build a piece of VBA ( or a macro) that I could run on the active cell to apply this conditional formatting, in particular how to make it cell-agnostic. For example: i would like to click on a cell, then click on a button in the QAT and have the conditional formatting applied, then select another cell and press on the same QAT button to have the same conditional formatting applied to the new cell.

Thanks!
 
Last edited:

Some videos you may like

Excel Facts

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.

footoo

Well-known Member
Joined
Sep 21, 2016
Messages
3,055
Office Version
  1. 2016
Platform
  1. Windows
Code:
Sub v()
If Selection.Count <> 1 Then Exit Sub
If Selection = 0 Then
    Selection.Interior.ColorIndex = 4
Else
    Selection.Interior.ColorIndex = 7
End If
End Sub
 

smozgur

BatCoder
Joined
Feb 28, 2002
Messages
1,121
If I understand correctly, you mean "creating conditional format for a cell" by using VBA. If that's the case, then following should help. It should be self descriptive, but let us know if any questions:

Code:
Sub setConditionalFormat()
Dim cll As Range
Dim fc As FormatCondition

    'Active cell
    Set cll = ActiveCell

    'First condition
    Set fc = cll.FormatConditions.Add(Type:=xlCellValue, Operator:=xlEqual, Formula1:=0)
    fc.Interior.Color = 10284031
    
    'Second condition
    Set fc = cll.FormatConditions.Add(Type:=xlCellValue, Operator:=xlNotEqual, Formula1:=0)
    fc.Interior.Color = 14348258
    
End Sub
 

smozgur

BatCoder
Joined
Feb 28, 2002
Messages
1,121
thanks Smozgur, exactly what I was after. I knew there had to be an elegant solution.

Glad to hear it helps.

In fact, it could have been two 1-liners instead bunch of assignments and codes, but I wanted to make readable and explain the FormatCondition object. In case you'd like to see the shorter version:

Code:
Sub setConditionalFormat()
    With ActiveCell.FormatConditions
        .Add(1, 3, 0).Interior.Color = 10284031
        .Add(1, 4, 0).Interior.Color = 14348258
    End With
End Sub
 

Watch MrExcel Video

Forum statistics

Threads
1,114,662
Messages
5,549,288
Members
410,908
Latest member
Allen P
Top