In VBA, If is a conditional statement that runs one block of code when a condition is True and optionally another block when it is False. You use it to make decisions in your macro, such as checking a cell value before performing an action.
What Does “If” Do in VBA?
The If statement evaluates an expression that returns either True or False. If the expression is True, VBA executes the statements that follow. If it is False, VBA skips those statements and moves to the ElseIf (if any), the Else block (if any), or the line after End If.
For example, this checks whether cell A1 contains the number 10:
If Range("A1").Value = 10 Then
MsgBox "A1 is 10"
End If
The condition Range("A1").Value = 10 returns True if the cell equals 10, so the message box appears; otherwise nothing happens.
Basic Syntax and Variations
The simplest form is a single-line If:
If condition Then statement
For multiple statements, use the block form with End If:
If condition Then
statement1
statement2
End If
To handle the False case, add Else:
If condition Then
' runs when True
Else
' runs when False
End If
For multiple conditions, chain ElseIf:
If score >= 90 Then
grade = "A"
ElseIf score >= 80 Then
grade = "B"
ElseIf score >= 70 Then
grade = "C"
Else
grade = "F"
End If
You can also write a single-line If...Else without End If:
If x > 0 Then result = "positive" Else result = "non-positive"
Common Uses in Real Macros
Most VBA code uses If to validate input, avoid errors, or branch based on data. Typical scenarios:
- Check if a cell is empty before processing it:
If IsEmpty(Range("A1")) Then Exit Sub - Check if a file exists before opening it:
If Dir("C:\temp\file.xlsx") <> "" Then Workbooks.Open ... - Check if a worksheet exists before referencing it:
If SheetExists("Data") Then ... - Compare text with case sensitivity:
If StrComp(str1, str2, vbBinaryCompare) = 0 Then
For example, to prevent a macro from running on a protected sheet:
If ActiveSheet.ProtectContents Then
MsgBox "Sheet is protected. Unprotect it first."
Exit Sub
End If
Using If with Logical Operators
Combine multiple conditions with And, Or, and Not:
If age >= 18 And age <= 65 Then
MsgBox "Working age"
End If
If choice = "yes" Or choice = "y" Then
MsgBox "Confirmed"
End If
If Not IsError(Range("A1")) Then
MsgBox "No error in A1"
End If
Be careful with operator precedence: And is evaluated before Or. Use parentheses to make the logic clear:
If (a > 0 And b > 0) Or (c > 0) Then
Common Mistakes and How to Avoid Them
Beginners often make these errors:
- Forgetting
End Ifin a blockIf– VBA will throw a syntax error. - Using
=instead ofIsfor object comparison – for objects like ranges, useIs:If Range("A1") Is Nothing Thenis wrong; actually you checkIf Range("A1") Is Nothingis only for object variables, not cell values. - Comparing text without case sensitivity – by default VBA is case-insensitive, but if you need exact case, use
StrCompwithvbBinaryCompare. - Using
Andin a single-lineIfwithout parentheses – it works, but readability suffers. - Not handling
Nothingfor object variables – always checkIf myObject Is Nothing Thenbefore using it.
Another classic bug: using If Range("A1") = "" Then to check for an empty cell. This works, but IsEmpty(Range("A1")) is more reliable because it also catches truly empty cells vs. a formula that returns an empty string.
If vs. Select Case: Which to Use?
When you have many conditions on the same variable, Select Case is often cleaner:
Select Case grade
Case "A"
MsgBox "Excellent"
Case "B"
MsgBox "Good"
Case Else
MsgBox "Keep trying"
End Select
Use If when conditions are complex (involving different variables or logical operators) or when you only have one or two checks. Select Case is faster and more readable for long lists of values.
Performance and Best Practices
For large datasets, avoid checking each cell with If in a loop if possible – use array formulas or AutoFilter. However, when you do use If inside loops, keep these tips in mind:
- Read cell values into variables first to avoid repeated worksheet access.
- Use
ElseIfinstead of nestedIfwhen conditions are mutually exclusive. - Exit early when a condition fails to avoid wasted processing.
- Use
Select Casefor long lists of discrete values.
Example of efficient loop:
Dim cell As Range
For Each cell In Range("A1:A1000")
If cell.Value > 100 Then
cell.Offset(0, 1).Value = "High"
ElseIf cell.Value > 50 Then
cell.Offset(0, 1).Value = "Medium"
Else
cell.Offset(0, 1).Value = "Low"
End If
Next cell
This is fine for 1000 rows, but for 100,000 rows, consider loading the range into an array first.
Frequently Asked Questions
Can I use If without End If? Yes, for a single-line If with one statement, you can omit End If. For block form, you must include it.
How do I check if a cell contains a specific text? Use If Range("A1").Value = "Yes" Then. For partial text, use InStr: If InStr(1, Range("A1").Value, "Yes", vbTextCompare) > 0 Then.
What is the difference between If and IIf? IIf is a function that returns one of two values based on a condition, but it evaluates both branches. Use If for statements; use IIf only for simple value assignments (though it can have side effects).
Can I use If to check for errors? Yes, use If IsError(value) Then or If Err.Number <> 0 Then after an operation.
Why does my If condition not work with text? VBA is case-insensitive by default, but if you have leading/trailing spaces, use Trim: If Trim(Range("A1").Value) = "Yes" Then.
Can I put multiple statements in a single-line If? Yes, separate them with colons: If x > 0 Then y = 1: z = 2, but it’s less readable than a block.
Related
- SQL Interview Queries for Experienced Developers
- Diagram of a 3 Cell Battery: Wiring & Layout
- Random Number Generator: How to Get a Random Order
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Access VBA MsgBox: Syntax, Buttons, and ExamplesIn Microsoft Access VBA, use MsgBox to display a message or ask a user a simple question; its…
- Excel VBA Rows: Select, Count, and Manage Worksheet RowsIn Excel VBA, Rows refers to worksheet rows or the rows within a specified range. For example, Worksheets("Data").Rows(5)…
- Excel VBA InputBox Function: Syntax and ExamplesThe Excel VBA InputBox function displays a dialog that asks a user for a response and returns that…
- Excel VBA Type Mismatch: Causes and FixesIn Excel VBA, “Run-time error 13: Type mismatch” means VBA tried to use a value as a different…
- How to Find VBA Code in Excel: Open and Search MacrosTo find VBA code in Excel for Microsoft 365 on Windows, open the workbook in the desktop app,…
- Excel VBA: Open a File Without Running MacrosTo open an Excel workbook without triggering its automatic macros, hold down Shift as you open it and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.