You can create a KPI in Excel with VBA by writing a short macro that reads your metric from a cell, compares it to a target, and then formats the cell (colour, icon, or message) based on the result. The macro can run on demand or automatically when the workbook opens or a cell changes. This guide walks through building a reusable KPI macro, adding conditional formatting via code, and handling common errors.
What You'll Need
- Excel for Windows or Mac (VBA is built in; no add-in required).
- A workbook with at least one metric cell and one target cell (for example, B2 for actual sales and C2 for the target).
- Basic familiarity with the VBA editor (Alt+F11 on Windows, Fn+Alt+F11 on some Macs).
- Macro security set to allow macros in this workbook (File > Options > Trust Center > Trust Center Settings > Macro Settings, or Excel > Preferences > Security on Mac). Labels can differ slightly by version and region.
Step-by-Step
- Open the VBA editor. Press Alt+F11 (Windows) or Fn+Alt+F11 (Mac). In the Project Explorer, right-click your workbook and choose Insert > Module. A blank module appears.
- Write the core KPI macro. Paste this code, adjusting the cell references to match your sheet:
This macro colours the actual cell green if it meets or beats the target, amber if within 90%, and red otherwise. Change the sheet name and cell addresses to suit your data.Sub UpdateKPI() Dim ws As Worksheet Dim actual As Double, target As Double Set ws = ThisWorkbook.Sheets("Dashboard") actual = ws.Range("B2").Value target = ws.Range("C2").Value If target = 0 Then ws.Range("B2").Interior.Color = RGB(255, 255, 0) Exit Sub End If If actual >= target Then ws.Range("B2").Interior.Color = RGB(0, 176, 80) ' green ElseIf actual >= target * 0.9 Then ws.Range("B2").Interior.Color = RGB(255, 192, 0) ' amber Else ws.Range("B2").Interior.Color = RGB(255, 0, 0) ' red End If End Sub - Run the macro. Close the editor, then press Alt+F8 (Windows) or Fn+Alt+F8 (Mac), select UpdateKPI, and click Run. The cell should change colour based on the values in B2 and C2.
- Make it update automatically (optional). To refresh the KPI whenever the actual or target changes, place this in the worksheet module (right-click the sheet tab > View Code):
This calls the macro only when B2 or C2 is edited, avoiding unnecessary recalculations.Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Me.Range("B2:C2")) Is Nothing Then UpdateKPI End If End Sub - Add a text status message. Extend the macro to write a label in D2:
Insert this before the End Sub line. The message gives a clear readout alongside the colour.If actual >= target Then ws.Range("D2").Value = "On track" ElseIf actual >= target * 0.9 Then ws.Range("D2").Value = "Watch" Else ws.Range("D2").Value = "Off track" End If - Use conditional formatting via VBA for a cleaner look. Instead of setting Interior.Color directly, you can add a rule that survives manual formatting changes:
Repeat for the amber and red thresholds. This approach keeps the KPI logic visible in the Conditional Formatting rules manager.With ws.Range("B2").FormatConditions .Add Type:=xlCellValue, Operator:=xlGreaterEqual, Formula1:="=$C$2" .Item(1).Interior.Color = RGB(0, 176, 80) End With - Test with edge cases. Set the target to zero, leave the actual blank, and enter text instead of a number. The macro should not crash; add error handling if needed:
This gives a friendly message instead of a runtime error dialog.On Error GoTo Cleanup ' ... your code ... Cleanup: If Err.Number <> 0 Then MsgBox "Check that B2 and C2 contain numbers." End Sub - Save the workbook as .xlsm. A standard .xlsx file discards macros. Use File > Save As and choose Excel Macro-Enabled Workbook (*.xlsm). On Mac, the same option appears in the Save As dialog.
Common Mistakes
- Forgetting to qualify the worksheet. Using Range("B2") without a sheet reference acts on the active sheet, which may not be the dashboard. Always use ws.Range or ThisWorkbook.Sheets("Name").Range.
- Comparing text to numbers. If B2 contains a number stored as text, the comparison may fail silently. Use Val() or check with IsNumeric before comparing.
- Division by zero. A target of zero causes an error when calculating percentages. Handle it explicitly, as shown in step 2.
- Saving as .xlsx. Macros vanish on save. Confirm the file type is .xlsm.
- Placing Worksheet_Change in a standard module. Event code must live in the sheet module, not a regular module, or it will never fire.
- Overwriting manual formatting. Setting Interior.Color each run wipes any manual fills. Conditional formatting rules avoid this.
Tips
- Name your ranges (Formulas > Define Name) such as Actual and Target, then reference them in code for readability.
- Keep thresholds in cells rather than hard-coding them, so users can adjust without editing VBA.
- Use a helper column to store the KPI status text, then build a chart or sparkline from it.
- Add a button (Developer > Insert > Button) and assign the macro so non-technical users can refresh with one click.
- Comment your code with the date and purpose; future you will thank you.
Troubleshooting
If the macro does nothing, check that macros are enabled for the workbook and that the sheet name in the code matches the tab exactly (including spaces). If you see a "Subscript out of range" error, the sheet name is wrong. If the cell colour changes but the wrong colour appears, verify the threshold logic and that B2 and C2 contain numbers, not text. If the Worksheet_Change event does not fire, confirm the code is in the sheet module and that EnableEvents has not been set to False by another macro. If the file will not save, switch to .xlsm. For runtime errors, use Debug > Compile VBAProject to catch syntax issues before running.
Frequently Asked Questions
Can I create a KPI without VBA?
Yes. Conditional formatting and icon sets can handle most colour-based KPIs without any code. VBA is useful when you need custom logic, automatic refresh, or status text.
Does VBA work on Excel for Mac?
Yes, Excel for Mac supports VBA, though some Windows-specific features (such as certain ActiveX controls) are not available. The core macro logic in this guide works on both.
How do I stop the macro from running on every change?
Restrict the Worksheet_Change event to specific cells using Intersect, as shown in step 4. This limits execution to the KPI input range.
Can I use VBA to create a KPI dashboard with multiple metrics?
Yes. Loop through a list of metric rows and apply the same comparison logic to each, writing results to adjacent status cells. Keep the threshold cells consistent across rows.
Why does my macro colour the wrong cell?
Check that the Range reference points to the intended cell and that the sheet is qualified. A common cause is running the macro while a different sheet is active.
Is VBA safe to use in shared workbooks?
Macros can carry risk, so only enable them from trusted sources and keep macro security at the recommended level. Share the .xlsm file only with people who need it.