Excel VBA IF Then Else

There are two ways to “excel vba if then else”: the quick way you copy and the durable way you understand. This page gives you both. The exact Excel answer is above; below, we build the small mental model that makes the fix stick, so the next variation of the same problem solves itself.

Exact answer

In Excel: Write If condition Then on its own line, put the action underneath, add ElseIf and Else branches as needed, and close the block with End If.

VBA macro: VBA If, ElseIf and Else

Sub GradeScores()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim score As Double
    Set ws = ActiveSheet
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    For i = 2 To lastRow
        If Not IsNumeric(ws.Cells(i, 1).Value) Then
            ws.Cells(i, 2).Value = "n/a"
        Else
            score = CDbl(ws.Cells(i, 1).Value)
            If score >= 90 Then
                ws.Cells(i, 2).Value = "A"
            ElseIf score >= 80 Then
                ws.Cells(i, 2).Value = "B"
            Else
                ws.Cells(i, 2).Value = "C"
            End If
        End If
    Next i
End Sub

The IsNumeric guard runs first so CDbl never receives text — a type-mismatch there is the usual cause of error 13 in grading code. Conditions are tested top to bottom and the first true branch wins, so >= 90 must precede >= 80.

How to run this macro

  1. Press Alt + F11 to open the VBA editor.
  2. Insert > Module.
  3. Paste the code above.
  4. Press F5, or close the editor and run it from Developer > Macros.
  5. Save the file as .xlsm so the macro is kept.
Annotated stepsExcel
1

Write If followed by the condition and the word Then, and press Enter.

2

Put each branch's actions on their own indented lines beneath it.

3

Add ElseIf condition Then for further cases, ordering them from most specific to most general.

4

Add a bare Else as the catch-all for everything unmatched — usually worth having even if only to flag surprises.

5

Close the block with End If, and run it against data containing an edge case as well as a normal value.

Ctrl+CthenCtrl+Shift+V+Cthen+Ctrl+VPaste values · WindowsMac

What this does

An If block is how a macro makes a decision. The block form spans several lines — If condition Then, the action, optional ElseIf and Else branches, then End If — and it is the form worth defaulting to, because it accepts multiple statements per branch and stays readable. There is also a single-line form, If x > 0 Then y = 1, which needs no End If but silently disallows anything else on the same line; mixing the two up is a common source of "Block If without End If". Branches are tested strictly top to bottom and the first true one wins, so ordering matters: putting a wide condition above a narrow one makes the narrow branch unreachable. Compound tests use And and Or, which in VBA evaluate both sides regardless of the first result — unlike many other languages, there is no short-circuiting, so a second test that would error on its own cannot be guarded by the first. The same idea underpins a lot of everyday Excel work, so the few minutes spent getting it right here pay back across every sheet you build afterwards. Treat it as a pattern, not a one-off, and it stops being something you look up and starts being something you reach for. Treat “excel vba if then else” as a small repeatable workflow rather than a one-off click you hope to remember next time. Use a small test block before the live file, so any surprise in the affected cells shows up while it is still harmless. When this is a ribbon command, the selection matters more than the button: confirm the range, apply the command, then spot-check the output before saving. That turns a workflow that saves repeating the same clicks every week into a method you can reuse, explain, and defend when the workbook leaves your screen.

A worked example

Column A holds exam scores and column B should hold a letter grade. Sub GradeScores() reads down to the last used row, checks each value is numeric, and applies three thresholds. The IsNumeric test comes first for a reason: a blank or a stray "absent" would make CDbl raise a type mismatch, and one bad cell stops the whole run. Note the branch order — 90 is also greater than 80, so if the >= 80 test came first every A would be graded B. To combine conditions, write If score >= 90 And attended = True Then. Because VBA evaluates both sides, If Not rng Is Nothing And rng.Value > 0 Then still errors when rng is Nothing; the safe form is nested Ifs, with the object check on the outside. A macro without conditions can only replay a fixed sequence — the If block is what lets it react to what is actually in the data. It is also where the subtle bugs live: branch order and the absence of short-circuit evaluation both produce code that runs cleanly and quietly returns the wrong answer. If there is any chance you will reuse this, drop it into a small template tab right now: a labelled input area on the left and the formula beside it, checked once against the tool above. Next time the same question comes up, the answer is a single paste away instead of a rebuild from memory.

In Google Sheets

Everything above works in Google Sheets too. Excel and Sheets share the formula syntax used here; only the surrounding menus are arranged differently. That portability is deliberate — learn it once and it follows you between the two tools and across Windows and Mac. Keep this page bookmarked for the next time the same question comes up. Better still, rebuild the example once in your own sheet — doing it yourself, with the tool above to check against, is what turns a copied formula into a technique you own. Here is the takeaway for “excel vba if then else”: copy the answer if you are busy, but if you have a spare few minutes, rebuild the example in Excel yourself with the tool above open beside it. That single pass — type it, run it, watch the result move when you change an input — is what turns a formula you found into a technique you trust. Keep your inputs labelled and referenced, never hard-coded, and the same sheet stays correct and auditable as it grows. Done that way, you will not need to look this up again, and you will be the person others ask.

Common mistakes

  • Ordering conditions from general to specific. The first true branch wins, so If score >= 80 placed above If score >= 90 makes the A branch dead code that never executes.
  • Expecting And and Or to short-circuit. VBA evaluates both operands every time, so a null-check joined by And does not protect the test after it — nest the Ifs instead.
  • Comparing to an empty cell with = "" and assuming it means empty. A cell holding a formula that returns "" passes that test while IsEmpty returns False; decide which of the two you actually mean.
  • Using a single-line If and then trying to add a second statement to it. The line silently does something else, or fails to compile — switch to the block form the moment a branch needs more than one action.
  • Testing text with = and being surprised by case. "Yes" = "yes" is False under the default Option Compare Binary; wrap both sides in LCase or set Option Compare Text at the top of the module.

Frequently asked questions

What is the difference between ElseIf and a nested If?

ElseIf continues the same block, so exactly one branch runs and there is a single End If. A nested If starts a new block inside a branch and needs its own End If. Use ElseIf for alternatives at the same level, nesting for a test that only makes sense after another passed.

Do I always need End If?

Only for the block form. The single-line version, If x > 0 Then y = 1, is self-closing — but it holds one statement, and any attempt to extend it is what produces the "Block If without End If" error.

When should I use Select Case instead?

When one value is being compared against many possible matches. A chain of more than three or four ElseIf tests against the same variable is almost always clearer as Select Case.

How do I test several conditions at once?

Join them with And or Or: If a > 0 And b > 0 Then. Both sides are always evaluated, so if one could raise an error on its own, nest the tests rather than combining them.