In Excel VBA, an If statement runs code only when a condition is true; use ElseIf for additional conditions and Else for the remaining cases. A basic block starts with If condition Then and ends with End If, letting a macro make decisions from values, worksheet data, or other conditions.
What an If statement does
An If statement is VBA’s basic branching tool. It lets a procedure choose between actions instead of executing the same instructions every time. For example, a macro might label a score as passing or failing, flag an order above a threshold, or skip a worksheet row when a required cell is blank.
The condition is an expression that evaluates to True or False. VBA checks it when the procedure reaches the statement. If it is true, VBA runs the associated instructions; if it is false, VBA moves to another branch, if one exists, or continues after the whole statement.
This is different from an Excel worksheet IF formula. A worksheet formula returns a value in a cell and recalculates as inputs change. A VBA If controls what a macro does while it runs. You can use both in the same workbook, but they serve different purposes.
Basic syntax: If, ElseIf, and Else
For multiple instructions or branches, use a block If. Put the first condition after If, add any additional tests with ElseIf, and finish with End If. The optional Else branch runs only if none of the preceding conditions is true. The order matters: VBA checks branches from top to bottom and runs the first matching branch.
This complete procedure assigns a label based on a score. With the example score of 72, it assigns “Pass” and prints that word in the Visual Basic Editor’s Immediate window.
Sub LabelScore()
' Assign a label based on a sample score.
Dim score As Double
Dim status As String
score = 72
If score >= 60 Then
status = "Pass"
ElseIf score >= 50 Then
status = "Borderline"
Else
status = "Fail"
End If
Debug.Print status
End Sub
In a block If, each condition line ends with Then, and the instructions to run go on the following lines. ElseIf is one word in VBA, not Else If. If you leave out Else, that is allowed: when all tests are false, VBA simply carries on after End If.
When to use a one-line If or a block
A single-line If is suited to one short action. Its form is If condition Then statement; an optional Else can add a second action on that same line. Unlike a block If, a single-line If does not use End If. Keeping it short makes it easy to see both the test and its effect at a glance.
For example, a short assignment based on a numeric test could fit on one line. If the branch needs several instructions, contains an ElseIf, or is likely to grow later, use a block instead. Block form is easier to indent, review, and debug. A long one-line statement can become difficult to read, particularly when it mixes several conditions or changes multiple cells.
- Use a one-line If for a simple, single action with an obvious result.
- Use a block If when you need several instructions, multiple alternatives, or room to add handling for unusual data.
- Use consistent indentation so the instructions belonging to each branch are clear.
VBA also permits a colon to separate statements on one line, but compressing a multi-step decision this way usually makes code harder to maintain. The goal is not to use the fewest lines; it is to make the decision and its consequences unambiguous.
Writing conditions and combining tests
Common comparison operators include = for equal to, <> for not equal to, and <, >, <=, and >= for numeric or comparable values. For example, a test can check whether a count is greater than zero or whether a status cell equals a particular word. Parentheses can make a condition’s intended grouping easier to understand.
Use And when both parts must be true and Or when either part can be true. Not reverses a Boolean condition. VBA also has operators such as Like for pattern comparisons and Is for object-reference comparisons, including checking whether an object variable is Nothing.
A detail that prevents a common bug: VBA’s And and Or do not short-circuit. That means VBA evaluates both sides, even when the first side already determines the logical result. Do not rely on a first test to protect an unsafe expression on the right. For instance, instead of combining “the denominator is not zero” with a division by that denominator, use one If to check for zero and a separate nested If to do the division only when it is safe.
For text comparisons, the module’s comparison setting matters. By default, VBA uses binary comparison, which distinguishes uppercase and lowercase letters. A module can use Option Compare Text to request text comparison that is not case-sensitive; this statement belongs at the top of the module, before procedures. Choose the behavior deliberately, especially when matching values entered by people.
Using If with worksheet cells
A worksheet-based condition often reads a cell’s Value and writes a result elsewhere. The example below checks values in column B of a sheet named Orders and writes a category to column C. It treats cell errors, blanks, numbers, and other text as separate cases, rather than assuming every cell contains a usable number.
Before running any macro, save a copy of the workbook: VBA changes cannot be undone with Ctrl+Z. This sample assumes the data starts in row 2 and that row 1 contains headings.
Sub CategorizeOrders()
' Categorize the values in column B on the Orders sheet.
Dim ws As Worksheet
Dim lastRow As Long
Dim r As Long
Dim cellValue As Variant
Set ws = ThisWorkbook.Worksheets("Orders")
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For r = 2 To lastRow
cellValue = ws.Cells(r, "B").Value
If IsError(cellValue) Then
ws.Cells(r, "C").Value = "Check error"
ElseIf Len(Trim$(CStr(cellValue))) = 0 Then
ws.Cells(r, "C").Value = "Blank"
ElseIf IsNumeric(cellValue) Then
If CDbl(cellValue) >= 1000 Then
ws.Cells(r, "C").Value = "Large"
Else
ws.Cells(r, "C").Value = "Standard"
End If
Else
ws.Cells(r, "C").Value = "Check text"
End If
Next r
End Sub
The order of checks is important. An Excel error value should be identified before trying to convert it to text or a number. The blank check then handles empty cells and cells containing only spaces. IsNumeric filters out text that cannot be treated as a number, and CDbl converts an accepted value before the numeric comparison. For a value of 1,250, the macro writes “Large”; for 700, it writes “Standard.”
The procedure uses ThisWorkbook, meaning the workbook containing the VBA code. If the macro is stored in a different workbook from the Orders sheet, that reference may not point where you intend. Confirm the sheet name and make a backup before adapting the example to important data.
Common mistakes and how to fix them
- Missing End If: Every block If needs a matching
End If. Nested If statements need their own matching endings. Indenting each block helps you spot a missing or misplaced line. - Using Else If instead of ElseIf: Write
ElseIfas one keyword when adding another branch to the same block. - Testing a blank or error as if it were a number: Worksheet cells can contain text, blanks, or error values. Check for errors and handle blanks before converting or comparing values.
- Incorrect branch order: A broad test placed before a narrower one may capture values you meant to handle separately. Put the most specific conditions first when their ranges overlap.
- Assuming And protects the second test: Both sides are evaluated in VBA. Split dependent checks into nested If statements when one expression could fail or cause an unwanted result.
- Comparing text without considering case: Check whether the module uses binary or text comparison, and make sure the chosen behavior matches the data.
When the result is unexpected, step through the procedure in the Visual Basic Editor and inspect the values used in the condition. On Windows, F8 steps through code one line at a time; on Mac, the equivalent can depend on the keyboard’s function-key settings. Breakpoints and the Immediate window can also help reveal whether a condition is false because of the data, a conversion, or the logic itself.
When Select Case is a better fit
Use Select Case when one expression is being compared with several distinct values or ranges. For example, mapping a department code to a department name may be clearer with one Case for each code than with a long chain of equality checks. A Case Else branch handles values not covered by the other cases.
An If block remains a better choice for unrelated tests, conditions involving different variables, or logic that combines several expressions with And and Or. Neither structure is universally faster or more correct; prefer the one that makes the decision easiest for someone to understand and verify.
Running VBA safely in Excel
VBA runs in the desktop versions of Excel, not in Excel for the web. Excel for Microsoft 365 on Windows can use the Visual Basic Editor from the Developer tab; Alt+F11 is the common Windows shortcut. In Excel for Microsoft 365 on Mac, use the Developer tab or Option+F11; some Mac keyboards require holding Fn as well. Ribbon availability and keyboard behavior can vary with setup.
To keep VBA code in a workbook, save it in a macro-capable format such as .xlsm. Excel may block macros or show a security notice, particularly for files from the internet or other untrusted locations. Enable macros only when you trust the source and understand what the code will do. A macro can change or delete worksheet data, and Ctrl+Z does not reverse those changes, so use a backup and test on a copy first.
Excel for Mac supports VBA, but some Windows-specific features, such as ActiveX controls and Windows API calls, are not portable to Mac. The examples here use ordinary worksheet objects, but check compatibility before moving a larger macro between platforms.
Frequently Asked Questions
What does If mean in Excel VBA?
An If statement checks whether a condition is true and runs the instructions for the matching branch. It controls macro behavior; it is not the same thing as an IF formula entered in a worksheet cell.
Do I need End If in VBA?
Use End If to close a block If, including blocks that contain ElseIf or Else. A single-line If has its statement on the same line and does not use End If.
Can VBA If have more than one ElseIf?
Yes. You can add multiple ElseIf branches before the optional Else. VBA tests them in order and runs the first branch whose condition is true.
What is the difference between ElseIf and Else?ElseIf introduces another condition to test. Else has no condition; it runs only when all the preceding If and ElseIf conditions are false.
Can Excel for the web run VBA macros?
No. Excel for the web does not run VBA macros. Use desktop Excel for VBA; a workbook may still contain VBA when opened in a browser, but the code will not execute there.
Related
- Link Two Data Validation Lists in Excel: Step-by-Step
- How to Insert a Line Across the Page in Microsoft Word
- How to Insert a Leader Line in Microsoft Word
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Add Comments in Excel VBA: Notes and Threaded CommentsTo add a cell note with Excel VBA, select the cell and run ActiveCell.AddComment "Check this value." in…
- Excel VBA Find Method: Syntax, Examples, and TipsIn Excel VBA, use the Range.Find method to search a range and return the first matching cell; if…
- Word VBA Mail Merge: How to Automate ItWord VBA can automate a mail merge by telling a prepared Word merge document to create a new…
- Excel VBA COUNTA: Count Nonblank Cells in MacrosIn Excel VBA, count nonblank cells with Application.WorksheetFunction.CountA and pass it a range. For example, Application.WorksheetFunction.CountA(Worksheets("Data").Range("A2:A100")) returns the…
- Excel VBA Hex: Convert Numbers and ColorsIn Excel VBA, use the Hex function to turn a number into its hexadecimal text representation: for example,…
- Excel VBA Evaluate: How It Works and When to Use ItIn Excel VBA, Application.Evaluate interprets a text expression using Excel’s formula language and returns the result as a…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.