VBA If Then Examples for Excel

VBA & macros · Updated November 3, 2026

VBA If Then Examples for Excel

VBA’s If...Then statement runs code when a condition is true, and can choose an alternative with Else or test further conditions with ElseIf. For example, If score >= 70 Then result = "Pass" Else result = "Fail" assigns a result based on a score; the examples below show the common forms and how to use them safely in Excel macros.

What VBA If Then Does

An If statement evaluates a condition as true or false. In Excel VBA, the condition can compare numbers, text, dates, cell values, or Boolean variables. When the condition is true, VBA runs the statement or block after Then. If it is false, VBA skips that block unless an Else or ElseIf branch provides another action.

VBA uses a single equals sign for both assignment and equality comparison, with the meaning determined by context. In score = 70 as a standalone statement, VBA assigns 70 to the variable. In If score = 70 Then, it tests whether the values are equal. The comparison operators you will use most often are:

  • = equal to, <> not equal to
  • > greater than, < less than
  • >= greater than or equal to, <= less than or equal to

Before running any macro that changes a workbook, save a separate copy first. Macro actions generally cannot be reversed with Ctrl+Z, so a backup is the practical way to protect the original data. Run code only in a workbook you trust.

Basic Single-Line and Block Forms

A single-line If is useful for one short action. The condition and action stay on the same line, and no End If is needed. This example displays a prompt if a name variable is empty:

Sub CheckCustomerName()
    Dim customerName As String

    customerName = ""
    If Len(Trim$(customerName)) = 0 Then MsgBox "Enter a customer name."
End Sub

Trim$ removes leading and trailing spaces, while Len checks how many characters remain. That makes the condition catch both an empty string and a value containing only spaces. The example sets the variable to an empty string so the result is predictable; in a real macro, the value could come from a worksheet cell or a user form.

For multiple actions, or whenever the logic needs an alternative, use a block form. A block starts with If and ends with End If:

Sub DescribeScore()
    Dim score As Double
    Dim message As String

    score = 82
    If score >= 70 Then
        message = "Pass"
        MsgBox message
    Else
        message = "Review needed"
        MsgBox message
    End If
End Sub

The indentation is not required for VBA to run, but it makes the branches easier to inspect. Use block form once a condition has more than one action; it is also less prone to mistakes when you later add another line.

Examples That Read and Write Worksheet Cells

A common use is checking a cell and writing a message to another cell. This example assumes the active worksheet has a score in B2 and writes a label in C2. It checks whether the entry is numeric before converting it, so text such as “pending” does not get passed to CDbl.

Sub LabelScoreInCell()
    Dim ws As Worksheet
    Dim score As Double

    Set ws = ActiveSheet
    If IsNumeric(ws.Range("B2").Value) Then
        score = CDbl(ws.Range("B2").Value)
        If score >= 70 Then
            ws.Range("C2").Value = "Pass"
        Else
            ws.Range("C2").Value = "Review"
        End If
    Else
        ws.Range("C2").Value = "Enter a number"
    End If
End Sub

Here, ws refers to the sheet that was active when the macro started. To avoid relying on whichever sheet happens to be selected, you can assign a specific worksheet instead, for example Set ws = ThisWorkbook.Worksheets("Scores"), if the workbook contains a sheet with that exact name. Qualifying the range through a worksheet variable also makes it clear which sheet the code reads and changes.

Be deliberate about the range being written to. A macro that fills C2 is limited in scope; a loop that writes down an entire column can affect many records. Test a new macro on a copy and a small sample before applying it to a full workbook.

Using ElseIf for Several Outcomes

Use ElseIf when conditions are alternatives and only one branch should run. VBA checks them in order and runs the first matching branch; it does not continue testing later branches after a match. Put the most meaningful thresholds in an order that makes the results unambiguous.

Sub ClassifyQuantity()
    Dim quantity As Long
    Dim category As String

    quantity = 12
    If quantity >= 20 Then
        category = "Large"
    ElseIf quantity >= 10 Then
        category = "Medium"
    ElseIf quantity > 0 Then
        category = "Small"
    Else
        category = "None"
    End If

    MsgBox category
End Sub

With a quantity of 12, the macro displays “Medium”: the first test is false and the second is true. Order matters. If the test for quantity > 0 came first, every positive quantity would be classified as “Small,” and the larger categories would never be reached. The final Else handles anything that did not match an earlier condition, including zero and negative values in this example.

Combining Conditions with And, Or, and Not

Logical operators let an If test more than one fact. And requires both conditions to be true; Or requires at least one; Not reverses a Boolean condition. For instance, a record might qualify only if its score reaches a threshold and its attendance is high enough:

Sub CheckEligibility()
    Dim score As Double
    Dim attendance As Double

    score = 78
    attendance = 0.9
    If score >= 70 And attendance >= 0.8 Then
        MsgBox "Eligible"
    Else
        MsgBox "Not eligible"
    End If
End Sub

VBA does not short-circuit And and Or: it evaluates both sides of the operator. This matters if the second expression could fail. For example, do not rely on denominator <> 0 And numerator / denominator > 2 to protect a division. Use nested If statements so the division only happens after the zero check:

Sub CheckRatio()
    Dim numerator As Double
    Dim denominator As Double

    numerator = 10
    denominator = 0
    If denominator <> 0 Then
        If numerator / denominator > 2 Then
            MsgBox "Ratio is above 2"
        Else
            MsgBox "Ratio is 2 or below"
        End If
    Else
        MsgBox "Cannot divide by zero"
    End If
End Sub

Nesting is also a useful way to handle validation in stages: first check that input exists, then check its type or range, and only then perform an operation that depends on it.

Putting If Inside a Loop

An If can appear inside a loop to make a decision for every item. This example counts numeric entries in A2:A20 on the active worksheet. It does not change the cells, and the count appears in a message box when the loop finishes.

Sub CountNumericEntries()
    Dim ws As Worksheet
    Dim rowNum As Long
    Dim numericCount As Long

    Set ws = ActiveSheet
    For rowNum = 2 To 20
        If IsNumeric(ws.Cells(rowNum, "A").Value) Then
            numericCount = numericCount + 1
        End If
    Next rowNum

    MsgBox numericCount & " numeric entries found."
End Sub

The variable rowNum identifies the current row, and numericCount increases only when the cell passes the test. A fixed end row is easy to understand, but it will not include data added below row 20. For a changing list, a macro can find the last used row first; choose that approach only after deciding how blank rows and unrelated content on the worksheet should be handled.

Common Errors and How to Avoid Them

Most problems with If statements come from syntax, ordering, or assumptions about the data. When VBA reports a compile error, check the structure before changing the condition.

  • Missing End If: Every multiline If block needs a matching End If. Nested blocks each need their own closing line.
  • Using ElseIf in the wrong order: VBA stops at the first true branch, so a broad condition can hide a more specific one below it.
  • Assuming text comparisons are always case-insensitive: String comparison behavior depends on the module’s Option Compare setting. The default is Binary, which distinguishes uppercase and lowercase. Option Compare Text makes text comparisons case-insensitive and must be declared at the top of a module, before procedures.
  • Passing unexpected cell contents to a conversion: A cell may contain text, be blank, or hold an error value. Validate input before converting or calculating with it, and handle worksheet errors if those are possible in your data.
  • Putting too much on one line: Single-line form is compact, but several conditions and actions on one line are harder to read and debug. Use an indented block for branching logic.

To diagnose a result that looks wrong, step through the procedure in the Visual Basic Editor and inspect the variables at each branch. On Windows, F8 runs the next statement in step mode; on Mac, the equivalent depends on the keyboard’s function-key settings. The editor is available from Excel’s Developer tab using Visual Basic. Check the actual cell value as well as its displayed appearance: formatting can make a number look like text or make a stored value appear rounded.

When to Use If Instead of Select Case

If...Then is a natural choice for ranges, compound tests, and conditions that combine different variables. For example, testing whether a date falls within a period or whether a value meets two independent requirements is usually clear with If and logical operators.

Select Case can be easier to read when one expression is being compared against several distinct values or ranges. It avoids repeating the expression in each branch. For example, a procedure that assigns different labels to a status such as “New,” “Open,” or “Closed” may be clearer with Select Case status. These are alternatives, not competing rules: use the form that makes the decision easiest to follow, and avoid deeply nested logic when a simpler structure would express the same behavior.

Frequently Asked Questions

What is the basic syntax for VBA If Then?
For one action, use If condition Then statement. For multiple lines or alternatives, use a block beginning with If condition Then and ending with End If; add Else or ElseIf when needed.

Do I need End If after every If statement?
Use End If for a multiline block. A single-line statement such as If score >= 70 Then MsgBox "Pass" does not use it. Nested multiline statements each need their own matching End If.

Can I use If Then in an Excel worksheet formula?
VBA’s If...Then is code for a macro, not worksheet formula syntax. In a worksheet cell, use Excel’s IF function instead. A VBA procedure can read or write worksheet cells while using an If statement to control its actions.

Does VBA And stop when the first condition is false?
No. VBA evaluates both sides of And, and both sides of Or. Use nested If blocks when the second test is unsafe unless the first test succeeds, such as checking a divisor before dividing.

How do I run a VBA If Then example?
In Excel for Microsoft 365 on Windows, open the Visual Basic Editor from Developer > Visual Basic, insert or choose a standard module, and place the procedure there. If the Developer tab is hidden, enable it through File > Options > Customize Ribbon. On Mac, use Developer > Visual Basic; the ribbon may need to be enabled first. Save a copy before running code because macro changes cannot be undone with Ctrl+Z.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.