3 Examples to Understand VBA If Or Operator
The Or operator in VBA is used to check multiple conditions. If any of the conditions is True, the code inside the If statement executes.
How to use VBA If Or operator?
The Or operator in VBA is used to check multiple conditions. If any of the conditions are True, the code inside the If statement executes.
This is unlike And operator where all conditions have to be True in order to execute the statements inside the If statement.
For example:
A = 10 Or C = 20
An example of Or operator in VBA
In this example, we have declared two variables and assigned values.
In the If statement, we checked the values of both variables with Or operator.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Sub Or_ex() Dim x, y x = 20 y = 40 If x = 20 Or y = 30 Then MsgBox "One or Both Conditions are True!" End If End Sub |
Result:
You can see, the value of x is 20 while y is not equal to 30, still code inside the If statement is executed and it displayed the message box.
Using three conditions in the If..Or
Now we have another variable value to test in the If..Or.
If any of the condition is True, it should execute the code inside If and display the message box – otherwise, nothing happens:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Sub Or_ex() Dim x, y, z x = 20 y = 40 z = 60 If x = 20 Or y = 30 Or z = 50 Then MsgBox "One, Two or All Conditions are True!" End If End Sub |
Output:
Though two conditions are False, it still executed If statement.
You may compare the Or with And operator by going to VBA And operator tutorial.
Using If..Or with Excel cells values
In this example, we will test the values of two Excel sheet cells.
If any of the conditions is True, it will apply the Blue font color to two rows, otherwise, red color will be applied:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Sub Or_ex() Dim prod1 As String, prod2 As String prod1 = Range("B3").Value prod2 = Range("B5").Value If prod1 = "Rice" Or prod2 = "Plates" Then Range("B3").EntireRow.Font.Color = vbBlue Range("B5").EntireRow.Font.Color = vbBlue Else Range("B3").EntireRow.Font.Color = vbRed Range("B5").EntireRow.Font.Color = vbRed End If End Sub |
Result:
You can see, the B3 value is Rice while B5 is Maze, still, it applied blue color to both rows.
Now, we will check B3 = Wheat and see the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
Sub Or_ex() Dim prod1 As String, prod2 As String prod1 = Range("B3").Value prod2 = Range("B5").Value If prod1 = "Wheat" Or prod2 = "Plates" Then Range("B3").EntireRow.Font.Color = vbBlue Range("B5").EntireRow.Font.Color = vbBlue Else Range("B3").EntireRow.Font.Color = vbRed Range("B5").EntireRow.Font.Color = vbRed End If End Sub |
Output:
As both conditions are False, so statements in the Else part executed and it made both rows red.