An If statement in Excel VBA runs one block of code only when a condition is true, so your macro can make decisions instead of marching through every line. The shortest working version is a single line: If Range("A1").Value > 10 Then MsgBox "Over the limit?". For anything longer than one action, you write a block statement that opens with If, closes with End If, and optionally adds ElseIf and Else branches. This guide walks through both forms, the comparison operators you will actually use, and the errors that stop macros from running.
What You'll Need
- Microsoft Excel for Windows or Mac, desktop version. The VBA editor is not available in Excel for the web or the mobile apps.
- A workbook saved as
.xlsm(Excel Macro-Enabled Workbook) before you save code, otherwise VBA will be discarded. - The Developer tab visible. If it is not, right-click the ribbon and choose Customize the Ribbon, then tick Developer in the right-hand list. The exact wording shifts slightly between versions and platforms.
- Macro security set to allow your own code. Check File > Options > Trust Center > Trust Center Settings > Macro Settings. On a Mac it sits under the Excel menu rather than File.
Step-by-Step
- Open the VBA editor with Alt+F11 on Windows, or Fn+Option+F11 on some Macs (the Developer tab's Visual Basic button works on both).
- In the Project window, right-click your workbook name, choose Insert > Module. A blank code pane opens. Standard modules are the right place for general macros; sheet modules are for event code such as Worksheet_Change.
- Start a procedure so the code has somewhere to live: type
Sub CheckValue()on the first line. Every block If must sit between a Sub and its matchingEnd Sub. - Write the simplest form first. On the next line type
If Range("A1").Value > 100 Then MsgBox "Large number"and press Enter. This one-line form needs no End If, which makes it handy for a single action but hard to read once you add more. - Convert it to a block statement for anything with two or more actions. Put
If Range("A1").Value > 100 Thenon its own line, then indented statements, thenEnd If. The editor will not indent for you automatically, so use Tab for readability. - Add an alternative with
Else. PlaceElseon its own line beforeEnd If; the statements under it run when the condition is false. Using Else is usually clearer than negating the condition. - Add more tests with
ElseIf. Order matters: VBA checks each condition top to bottom and runs only the first match, then jumps to End If. Put the narrowest conditions first. A typical chain tests> 1000, then> 100, then> 0, with a final Else for everything else. - Pick the right comparison operator.
=tests equality (unlike in a formula where it is the only equals),<>means not equal, and>,<,>=,<=behave as you expect. Join tests withAnd,Or, andNot, wrapping groups in parentheses when you mix them. - Handle blank cells deliberately. An empty cell has
.Value = ""for text comparisons but behaves as zero in numeric comparisons, soIf Range("A1").Value = 0 Thenis true for an empty cell. TestIsEmpty(Range("A1").Value)when blank versus zero must be distinguished. - Test text against a case-insensitive comparison or use
StrCompwith the compare argument for exact matching. By default VBA treats "apple" and "Apple" as equal, which is exactly what you want for user-entered data but can surprise you in lookups. - Run the macro with F5 while the cursor is inside the Sub, or place the cursor on a line and press F8 to step through one statement at a time. F8 is the fastest way to see which branch is actually taken.
- Save the workbook as .xlsm and, if the macro should be one-click, assign it to a button from the Developer tab's Insert controls.
Common Mistakes
- Putting code after a one-line If on the same line. Only the first statement is conditional; anything after it runs regardless. Use a block If instead.
- Forgetting
End If. The editor usually flags this with a compile error, but nested Ifs make it easy to close the wrong one. Indent consistently so each End If lines up with its If. - Writing
Thenafter ElseIf. The syntax isElseIf condition Thenbut plainElsetakes nothing after it. - Comparing text to a number.
If Range("A1").Value > 5 Thenagainst the text "10" returns an unexpected result because VBA compares text strings character by character. Convert withCLng,CDbl, orValfirst. - Testing the wrong sheet. An unqualified
Rangerefers to the active sheet, so the macro breaks the moment somebody clicks a different tab. Qualify it:Worksheets("Data").Range("A1").Value. - Checking only one cell when the user selected a range. Use a loop over the cells, or test
Target.Countfirst in event code.
Tips
- Prefer an explicit comparison such as
If x = True Thenover bareIf x Thenwhen x might be an error or a number; bare truthiness can hide bugs. - Use
Select Caseinstead of a long ElseIf chain that tests the same variable dozens of times. It reads far better and is easier to extend. - Wrap risky conditions so a worksheet error does not halt the macro: check
IsError, or convert withCVErr-aware helpers. - Comment the intent above each branch rather than restating the code, for example "flag stock below reorder point".
- Keep conditions on one line where they stay readable; break long
And/Orchains onto separate lines with a space before the underscore continuation. - Store the tested value in a variable first (
Dim v As Variant: v = Range("A1").Value) when the same cell feeds several conditions. It avoids repeated worksheet reads and makes F8 stepping easier to follow.
Troubleshooting
If the macro does nothing at all, check that you are on the right sheet and that the cell actually contains the value you expect. Click the cell and read the formula bar; a typed 10 pasted as text will fail numeric comparisons. Turn on Debug > Step Into and press F8 to watch the yellow execution line move.
A "Compile error: Expected: End of statement" almost always points at a missing bracket, a missing Then, or an apostrophe swallowed inside a string. Look at the line the editor highlights, not the one after it.
If a runtime error reports type mismatch, a cell holds text where the code wants a number, or an empty value reached a numeric comparison. Add a guard such as If Not IsNumeric(Range("A1").Value) Then Exit Sub before the test.
If the macro works on your machine but not a colleague's, the usual causes are a disabled macro, a different active sheet, or regional settings that store the separator differently. Ask them to check the Trust Center and to select the intended sheet first. When in doubt, add a deliberate error message that prints the tested value so the actual state is visible.
Frequently Asked Questions
Do I need And If for every condition?
No. One block If can hold several conditions joined by And or Or, and each ElseIf adds one more test. You only close the whole structure with a single End If.
What is the difference between ElseIf and Else?
ElseIf adds another condition to test; Else catches everything that reached it, with no condition. Only one branch in a chain ever runs.
Can an If statement test more than one cell at once?
Not directly. Test each cell separately, use WorksheetFunction.CountIf, or loop over the range with a For Each loop.
Why does my If always take the Else branch?
Most often the cell is on a different sheet than the active one, or the value is text rather than a number. Qualify the sheet and convert the value before comparing.
Is If the same as IF in a worksheet formula?
No. Worksheet IF is a function that returns a value; VBA If is a control statement that decides which statements run. They are unrelated beyond the name.
Can I exit a macro early from inside an If?
Yes. Use Exit Sub inside the branch; execution leaves the procedure immediately and skips every later line.