In Excel VBA, use the Or operator between complete conditions inside an If statement: If status = "Open" Or status = "Pending" Then. The condition is true when either comparison is true; write out each comparison rather than listing extra values on their own.
VBA Or syntax and meaning
The basic structure is If condition1 Or condition2 Then, followed by the instructions to run when the combined condition is true. You can add an optional Else branch and close the statement with End If. In VBA, Or is a logical operator: for Boolean conditions, the combined result is true if at least one condition is true.
For example, if a procedure should handle requests in either of two statuses, compare the status variable with each allowed value:
Sub CheckRequestStatus()
Dim status As String
status = "Pending"
' Handle either accepted status.
If status = "Open" Or status = "Pending" Then
MsgBox "This request can be processed."
Else
MsgBox "This request is not ready."
End If
End Sub
Here, status = "Open" is false, while status = "Pending" is true, so the message in the If branch appears. VBA is not case-sensitive about the spelling of keywords such as If and Or, but how text values compare can depend on the module’s comparison setting, as explained below.
Use a complete comparison for every alternative
A common mistake is to write If status = "Open" Or "Pending" Then. The second item is not a comparison with status. VBA does not automatically understand it as “status equals Pending,” and the expression can cause a type mismatch. Repeat the variable and comparison operator instead:
If status = "Open" Or status = "Pending" Then
The same rule applies when checking numbers, text, dates, or Boolean variables. For example, if score is a number and either a very low or a very high score should trigger a review, express both comparisons explicitly:
If score < 50 Or score > 90 Then
That condition is true for values below 50 or above 90; values from 50 through 90 do not meet either test. The comparison operators belong to each individual condition. This makes the code easier to read and prevents accidental interpretation of a standalone value as a condition.
Combine Or with other conditions
You can combine Or with And when a rule contains alternatives as well as requirements. Suppose a task should be marked for review only when it is active and its region is East or West. Parentheses make the intended grouping clear:
Sub CheckTask()
Dim region As String
Dim isActive As Boolean
region = "East"
isActive = True
' Require an active task in either region.
If (region = "East" Or region = "West") And isActive Then
MsgBox "Review this task."
End If
End Sub
The parentheses group the regional alternatives before the result is combined with isActive. Without parentheses, VBA follows its operator precedence rules, where And is evaluated before Or. That can produce a different result than a reader expects. When a condition mixes logical operators, add parentheses to show the rule rather than relying on readers to remember precedence.
For example, a Or b And c is interpreted as a Or (b And c), not as (a Or b) And c. Those expressions are not equivalent in every situation. Grouping also helps when a rule grows to include more values, flags, or comparisons.
VBA Or does not short-circuit
A particularly important VBA detail is that Or evaluates both sides of the expression. It does not stop as soon as the first condition is true. VBA also evaluates both sides of And; it has no OrElse or AndAlso short-circuit operators like some other programming languages.
This matters if the second condition can fail or cause an unwanted action. For example, do not rely on If denominator <> 0 And numerator / denominator > 2 Then to protect a division by zero. VBA may evaluate the division even when the denominator is zero. Put the risky operation in a nested test instead:
Sub CheckRatio()
Dim denominator As Double
Dim numerator As Double
denominator = 0
numerator = 10
' Check the divisor before calculating the ratio.
If denominator <> 0 Then
If numerator / denominator > 2 Then
MsgBox "The ratio is above the limit."
End If
End If
End Sub
Here, the inner comparison is reached only after the outer If establishes that the denominator is not zero. Use this pattern for expressions that can raise an error, call a function with side effects, or depend on an object being set. A simple comparison such as a status check is safe to combine with Or.
Use Or in a worksheet-based macro
In a macro that checks cells row by row, the same operator works with values read from the worksheet. This example checks column B for either of two priority labels and writes a note in column C. It assumes a worksheet named Tasks, a header in row 1, and priority values in column B.
Save a copy of the workbook before running a macro: VBA changes cannot be undone with Ctrl+Z. The procedure below writes to cells in column C, so verify the sheet and output column before running it.
Sub LabelUrgentRows()
Dim ws As Worksheet
Dim lastRow As Long
Dim rowNum As Long
Dim priority As String
Set ws = ThisWorkbook.Worksheets("Tasks")
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
' Mark rows with either priority label.
For rowNum = 2 To lastRow
priority = CStr(ws.Cells(rowNum, "B").Value)
If priority = "High" Or priority = "Urgent" Then
ws.Cells(rowNum, "C").Value = "Review"
End If
Next rowNum
End Sub
The Or check belongs inside the loop, so VBA tests each row’s priority. CStr converts the cell value to text before comparing it. If the sheet name is different, change "Tasks" to the actual worksheet name. If column C contains information that must be kept, choose another output column or change the macro before running it.
Common comparison and logic problems
- Missing comparison: Write
priority = "High" Or priority = "Urgent", notpriority = "High" Or "Urgent". - Wrong operator: Use
Orwhen either condition is sufficient. UseAndwhen both conditions must be true. - Unexpected grouping: Add parentheses around alternatives when combining
OrwithAnd. - Text case: By default, VBA modules use binary text comparison unless an
Option Comparestatement changes the setting. Binary comparison distinguishes uppercase and lowercase text.Option Compare Textmakes text comparisons case-insensitive in that module. Place it at the top of the module, before procedures, if that behavior is appropriate. - Blank or inconsistent cell contents: A cell may contain a number, an error value, or extra spaces rather than the expected text. Check and normalize data if comparisons do not behave as intended; converting every value to text does not remove spaces or make an error value ordinary text.
When debugging, step through the procedure with the VBA editor’s debugging tools and inspect the values of the variables involved. A condition can be syntactically correct but false because a cell has a trailing space, a different value, or a different data type than expected.
When Select Case or the worksheet OR function is clearer
If you are comparing one variable with several possible values, Select Case can be easier to scan than a long chain of Or comparisons. It supports multiple values on a Case line:
Sub CheckStatusWithSelectCase()
Dim status As String
status = "Pending"
' Group values that lead to the same action.
Select Case status
Case "Open", "Pending"
MsgBox "This request can be processed."
Case Else
MsgBox "This request is not ready."
End Select
End Sub
Use Or when the conditions are different, such as a text match or a separate numeric threshold. Use Select Case when many alternatives test the same expression. For a worksheet cell formula, Excel has a separate OR function; that is not VBA syntax.
With the status in cell A2 and the example value Pending, the worksheet formula =OR(A2="Open",A2="Pending") returns TRUE. In a VBA procedure, write the logical operator directly between comparisons; in a worksheet formula, call the OR function with comma-separated arguments.
Where to write and run VBA
For Excel for Microsoft 365 on Windows, open the Visual Basic Editor with Alt+F11. You can insert a standard module in the editor and place a procedure there. To run a macro, use the editor’s Run command or return to Excel and choose Developer > Macros, select the macro, and choose Run. If the Developer tab is not visible, enable it through File > Options > Customize Ribbon.
Excel for Mac also includes a VBA editor, usually opened with Option+F11; depending on the keyboard, you may need Fn+Option+F11. Ribbon locations and some VBA capabilities differ on Mac, and code that depends on Windows-specific components may need changes. Excel for the web does not create or run VBA macros, so use the desktop Excel application for these procedures. Macro security settings may also block a file’s code; only enable macros in workbooks you trust.
Frequently Asked Questions
Can I put more than two conditions after Or?
Yes. Write a complete comparison for each alternative, such as code = "A" Or code = "B" Or code = "C". For a long list of values all compared with one variable, consider Select Case for readability.
What is the difference between Or and And in VBA?Or makes the combined condition true when at least one Boolean condition is true. And requires every condition to be true. Both sides are evaluated in VBA, so neither operator should be used to guard an expression that could fail.
Can I use Or with a range or a cell value?
Yes. Read a cell’s value into a variable or compare the cell value directly, then place Or between full comparisons. Make sure the value’s type and contents match what the condition expects.
Why does my Or condition seem to ignore uppercase and lowercase?
Check the module’s Option Compare setting. The default binary comparison distinguishes case, while Option Compare Text makes string comparisons case-insensitive for that module. Also check whether the values contain spaces or other unexpected characters.
Does VBA Or stop after the first true condition?
No. VBA evaluates both sides of Or. If a later expression could cause an error, separate the checks into nested If statements so the risky expression is reached only when it is safe.
Related
- Excel MAXIFS: Find the Highest Value for Each Date
- Excel Tabs: How to Find Duplicate Names Across Sheets
- Excel SUM with Multiple Criteria: How to Do It
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA MsgBox Width: What You Can and Can’t ControlVBA’s MsgBox has no width argument or width property, so you cannot set its exact dimensions directly. Its…
- Access VBA MsgBox Constants: Buttons, Icons and ResultsAccess VBA uses the built-in MsgBox function to show a message and, optionally, buttons, an icon, and a…
- Access VBA Error Handling: Trapping and Fixing ErrorsAccess VBA error handling lets a procedure respond when a runtime error occurs instead of stopping unexpectedly. Use…
- Excel VBA Hex: Convert Numbers and ColorsIn Excel VBA, use the Hex function to turn a number into its hexadecimal text representation: for example,…
- VBA Range Column: How to Reference ColumnsIn VBA, reference a whole worksheet column with Columns("C") or Range("C:C"); to get the column containing a particular…
- Excel Analysis ToolPak VBA: Setup, Limits, and UseYes—Excel can work with the Analysis ToolPak and VBA, but the add-in is not a universal VBA interface…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.