You can apply conditional formatting through VBA by using an If statement to test a cell's value, then adding a FormatCondition to the range with xlCellValue or xlExpression and setting its Interior.Color or Font.Color. The shortest working pattern is: If Range("A1").Value > 10 Then Range("A1").Interior.Color = vbRed — but for true conditional formatting that updates automatically, use Range("A1:A10").FormatConditions.Add inside your If block. This guide covers both approaches, the correct syntax, and how to avoid the most common errors.

What You'll Need

  • Excel with the Developer tab enabled (File > Options > Customize Ribbon > check Developer).
  • A workbook saved as .xlsm (macro-enabled) if you want the code to persist.
  • Basic familiarity with the VBA Editor (Alt+F11) and the Immediate Window (Ctrl+G).

Step-by-Step

  1. Open the VBA Editor. Press Alt+F11. In the Project pane, right-click your workbook and choose Insert > Module. This is where your code will live. Menu labels can differ slightly by Excel version and region.
  2. Write a simple If test. Type a Sub that checks a cell value and colors it directly. For example:
    Sub ColorIfRed()
        If Range("A1").Value > 10 Then
            Range("A1").Interior.Color = vbRed
        Else
            Range("A1").Interior.ColorIndex = xlNone
        End If
    End Sub
    This is a one-time action, not a live rule. Press F5 to run it.
  3. Add a real conditional format inside the If block. To create a rule that updates when the cell changes, use FormatConditions.Add. The two most useful types are xlCellValue (compare to a value) and xlExpression (use a formula). Example:
    Sub AddRuleIfNeeded()
        Dim rng As Range
        Set rng = Range("A1:A10")
        rng.FormatConditions.Delete
        If Range("B1").Value = "Yes" Then
            With rng.FormatConditions.Add(Type:=xlCellValue, _
                  Operator:=xlGreater, Formula1:="10")
                .Interior.Color = RGB(255, 199, 206)
                .Font.Color = RGB(156, 0, 6)
            End With
        End If
    End Sub
    The If statement controls whether the rule is added; the rule itself controls which cells get highlighted.
  4. Use xlExpression for formula-based rules. When your condition depends on another cell or a function, switch to xlExpression and supply a formula string that returns TRUE or FALSE. For example, to highlight rows where column B equals "Overdue":
    With Range("A1:A10").FormatConditions.Add(Type:=xlExpression, _
          Formula1:="=$B1=\"Overdue\"")
        .Interior.Color = vbYellow
    End With
    Note the relative reference $B1 — the row is relative so the rule follows each row.
  5. Clear existing rules before adding new ones. Call rng.FormatConditions.Delete at the start of your Sub, otherwise repeated runs stack duplicate rules and slow the workbook.
  6. Test with a breakpoint. Click in the left margin next to a line to set a breakpoint (a red dot), then press F5. Step through with F8 to confirm your If condition evaluates as expected.
  7. Save as .xlsm. Use File > Save As and choose Excel Macro-Enabled Workbook. A standard .xlsx save will strip the code.

Common Mistakes

  • Using = instead of := for named arguments. Type:=xlCellValue is correct; Type=xlCellValue causes a syntax error.
  • Forgetting to delete old rules. Running the same macro repeatedly piles up identical FormatConditions, which can make the sheet sluggish.
  • Quoting formulas incorrectly. Formula1 strings need doubled quotes inside VBA strings: "=$B1=\"Overdue\"".
  • Confusing a one-time color change with a conditional format. Setting .Interior.Color directly does not update when the cell value changes; only FormatConditions rules do.
  • Using absolute references in xlExpression when relative is needed. $B$1 locks the row and the rule will not follow down the column.
  • Leaving the wrong sheet active. Unqualified Range("A1") refers to the active sheet; qualify with Worksheets("Sheet1").Range("A1") for reliability.

Tips

  • Use RGB() instead of vbRed for exact brand colors.
  • Set .StopIfTrue = True when you have multiple rules on the same range and want the first match to win.
  • Loop through a range with For Each cell In rng when each cell needs a different condition, but prefer a single FormatCondition with a formula for speed.
  • Record a macro (Developer > Record Macro) while applying conditional formatting manually to see the exact syntax Excel generates for your version.
  • Keep rule formulas short; long formulas are hard to debug and slow to evaluate on large ranges.

Troubleshooting

  • "Compile error: Expected: expression" — usually a missing Then or a mismatched End If. Check every If has a matching End If.
  • Rule added but nothing highlights — confirm the formula returns TRUE for the cells you expect. Type the same formula into a blank cell to test it.
  • Runtime error 1004 — often a bad range reference or a sheet name that does not exist. Verify the sheet name exactly, including spaces.
  • Macro does nothing — check macros are enabled (File > Options > Trust Center > Trust Center Settings > Macro Settings) and that you saved as .xlsm.
  • Rules vanish after reopening — the workbook was saved as .xlsx. Re-save as .xlsm.
  • Slow performance — wrap the Sub with Application.ScreenUpdating = False at the start and True at the end, and delete duplicate rules.

Frequently Asked Questions

Can I use an If statement inside a conditional formatting formula?

Yes. In an xlExpression rule, write a formula like =IF($A1>10,TRUE,FALSE). Simpler still, drop the IF and use the logical test directly: =$A1>10.

What is the difference between xlCellValue and xlExpression?

xlCellValue compares the cell to a fixed value or formula result using an operator (greater than, equal to, between). xlExpression evaluates a full formula that must return TRUE or FALSE, which lets you reference other cells and functions.

How do I remove a conditional format added by VBA?

Call Range("A1:A10").FormatConditions.Delete to remove all rules on that range, or use .FormatConditions(1).Delete to remove a specific rule by index.

Why does my If block run but the formatting not appear?

Most often the condition is FALSE at runtime. Add a Debug.Print Range("B1").Value line before the If and check the Immediate Window (Ctrl+G) to see the actual value.

Can I apply conditional formatting to an entire row based on one cell?

Yes. Select the full row range (e.g. A1:D10), add an xlExpression rule with a formula like =$B1="Overdue", using a mixed reference so the column is locked and the row is relative.

Does conditional formatting added by VBA survive a copy to another workbook?

Yes, if you copy the cells (not just values) the rules travel with them. Copying only values strips the formatting. Re-run your macro in the target workbook if needed.