IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.
IF OR Function in VBA
Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.
Table of contents
- IF OR Function in VBA
- How to Use IF with OR Function in VBA?
- IF OR VBA Function with Loops (Advanced)
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)
How to Use IF with OR Function in VBA?
We will show you a simple example of using the IF OR function in VBA.
You can download this VBA IF OR Excel Template here – VBA IF OR Excel Template
A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.
Now, look at the syntax of the IF OR function in VBA.
[Test] OR [Test] OR [Test]
It is the same as we saw in the worksheet example. For a better understanding, look at the below example.
We have the previous month’s price, the last 6-month average price, and the current monthly price here.
To decide whether to buy the product, we need to do some tests here, and those tests are.
If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”
Step 1: Open the IF condition inside the Sub procedure.
Code:
Sub IF_OR_Example1() If End Sub
Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value <= Range(“B2”).Value
Code:
Sub IF_OR_Example1() If Range(“D2”).Value <= Range(“B2”).Value End Sub
Step 3: The first logical condition completes. Now, open OR statement.
Code:
Sub IF_OR_Example1() If Range("D2").Value <= Range("B2").Value OR End Sub
Step 4: Now, apply the second logical condition as Range(“D2”).Value <= Range(“C2”).Value
Code:
Sub IF_OR_Example1() If Range("D2").Value <= Range("B2").Value OR Range("D2").Value <= Range("C2").Value End Sub
Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”
Code:
Sub IF_OR_Example1() If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then End Sub
Step 6: In the next line, write what the result should be if the logical testA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.
Code:
Sub IF_OR_Example1() If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then Range("E2").Value = "Buy" End Sub
Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.
Code:
Sub IF_OR_Example1() If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then Range("E2").Value = "Buy" Else Range("E2").Value = "Do Not Buy" End Sub
Step 8: Close the IF statement with “End If.”
Code:
Sub IF_OR_Example1() If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then Range("E2").Value = "Buy" Else Range("E2").Value = "Do Not Buy" End If End Sub
We complete the coding part.
Let us run this code using F5 or manually through the run option and see the result in cell E2.
We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.
IF OR VBA Function with Loops (Advanced)
Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loopsA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more.
We have added a few more lines for the above data set.
We need to use the For Next Loop here.
Just keep the current code as it is.
Declare the variable as an Integer.
Now, open For Next Loop from 2 to 9.
Now, wherever we have cell referenceCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more, change the current number, and concatenate the variable “k” with them.
For example, Range (“D2”).Value should be Range (“D” & k).Value
Now, run the code. First, we should get the status in all the cells.
You can copy the code below.
Code:
Sub IF_OR_Example1() Dim k As Integer For k = 2 To 9 If Range("D" & k).Value <= Range("B" & k).Value Or Range("D" & k).Value <= Range("C" & k).Value Then Range("E" & k).Value = "Buy" Else Range("E" & k).Value = "Do Not Buy" End If Next k End Sub
Recommended Articles
This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –
- VBA INT
- VBA LEN
- VBA Integer
- VBA MID Function
Home / VBA / VBA IF OR (Test Multiple Conditions)
You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.
Use OR with IF
- First, start the IF statement with the “IF” keyword.
- After that, specify the first condition that you want to test.
- Next, use the OR keyword to specify the second condition.
- In the end, specify the second condition that you want to test.
To have a better understanding let’s see an example.
Sub myMacro()
'two conditions to test using OR
If 1 = 1 Or 2 < 1 Then
MsgBox "One of the conditions is true."
Else
MsgBox "None of the conditions are true."
End If
End Sub
If you look at the above example, we have specified two conditions one if (1 = 1) and the second is (2 < 1), and here only the first condition is true, and even though it has executed the line of code that we have specified if the result is true.
Now let’s see if both conditions are false, let me use a different code here.
Sub myMacro()
'two conditions to test using OR
If 1 = 2 Or 2 < 1 Then
MsgBox "One of the conditions is true."
Else
MsgBox "None of the conditions are true."
End If
End Sub
In the above code, both conditions are false, and when you run this code, it executes the line of code that we have specified if the result is false.
In the same way, you can also test more than two conditions at the same time. Let’s continue the above example and add the third condition to it.
Sub myMacro()
'three conditions to test using OR
If 1 = 1 And 2 > 1 And 1 - 1 = 0 Then
MsgBox "one of the conditions is true."
Else
MsgBox "none of the conditions are true."
End If
End Sub
Now we have three conditions to test, and we have used the OR after the second condition to specify the third condition. As you learned above that when you use OR, any of the conditions need to be true to get true in the result. When you run this code, it executes the line of code that we have specified for the true.
And if all the conditions are false, just like you have in the following code, it returns false.
Sub myMacro()
'three conditions to test using OR
If 1 < 1 And 2 < 1 And 1 + 1 = 0 Then
MsgBox "one of the conditions is true."
Else
MsgBox "none of the conditions are true."
End If
End Sub
No, you didn’t:
If Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
An alternative would be to use a Select Case
statement. These are especially useful if you have many conditions to test:
Select Case Cells(i, 3).Value
Case "BRITISH TELECOM", _
"CHRISTIES INTERNATIO", _
"DTAG", _
"IMAGINE COMMUNICATIONS CORP"
'Do something
Case "Some other string", _
"and another string"
'Do something else
Case Else
'Do something if none of the other statements evaluated to True
End Select
That Select Case
statement would be equivalent to the following If
statement:
If Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
'Do something
ElseIf Cells(i, 3).Value = "Some other string" Or _
Cells(i, 3).Value = "and another string" Then
'Do something else
Else
'Do something if none of the other statements evaluated to True
End If
Unrelated to the actual question, but in response to a further question in comments:
If you have error values in your data, they will not be able to be compared to Strings, so you will need to test for errors first.
For example:
If IsError(Cells(i, 3).Value) Then
'Do whatever you want to do with error values such as #N/A
ElseIf Cells(i, 3).Value = "BRITISH TELECOM" Or _
Cells(i, 3).Value = "CHRISTIES INTERNATIO" Or _
Cells(i, 3).Value = "DTAG" Or _
Cells(i, 3).Value = "IMAGINE COMMUNICATIONS CORP" Then
'...
or
If IsError(Cells(i, 3).Value) Then
'Do whatever you want to do with error values such as #N/A
Else
Select Case Cells(i, 3).Value
Case "BRITISH TELECOM", _
"CHRISTIES INTERNATIO", _
"DTAG", _
"IMAGINE COMMUNICATIONS CORP"
'Do something
Case "Some other string", _
"and another string"
'Do something else
Case Else
'Do something if none of the other statements evaluated to True
End Select
End If
In this Article
- VBA If Statement
- If Then
- ElseIF – Multiple Conditions
- Else
- If-Else
- Nested IFs
- IF – Or, And, Xor, Not
- If Or
- If And
- If Xor
- If Not
- If Comparisons
- If – Boolean Function
- Comparing Text
- VBA If Like
- If Loops
- If Else Examples
- Check if Cell is Empty
- Check if Cell Contains Specific Text
- Check if cell contains text
- If Goto
- Delete Row if Cell is Blank
- If MessageBox Yes / No
- VBA If, ElseIf, Else in Access VBA
VBA If Statement
If Then
VBA If Statements allow you to test if expressions are TRUE or FALSE, running different code based on the results.
Let’s look at a simple example:
If Range("a2").Value > 0 Then Range("b2").Value = "Positive"
This tests if the value in Range A2 is greater than 0. If so, setting Range B2 equal to “Positive”
Note: When testing conditions we will use the =, >, <, <>, <=, >= comparison operators. We will discuss them in more detail later in the article.
Here is the syntax for a simple one-line If statement:
If [test_expression] then [action]
To make it easier to read, you can use a Line Continuation character (underscore) to expand the If Statements to two lines (as we did in the above picture):
If [test_expression] then _
[action]
If Range("a2").Value > 0 Then _
Range("b2").Value = "Positive"
End If
The above “single-line” if statement works well when you are testing one condition. But as your IF Statements become more complicated with multiple conditions, you will need to add an “End If” to the end of the if statement:
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
End If
Here the syntax is:
If [test_expression] then
[action]
End If
The End If signifies the end of the if statement.
Now let’s add in an ElseIF:
ElseIF – Multiple Conditions
The ElseIf is added to an existing If statement. ElseIf tests if a condition is met ONLY if the previous conditions have not been met.
In the previous example we tested if a cell value is positive. Now we will also test if the cell value is negative with an ElseIf:
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
Range("b2").Value = "Negative"
End If
You can use multiple ElseIfs to test for multiple conditions:
Sub If_Multiple_Conditions()
If Range("a2").Value = "Cat" Then
Range("b2").Value = "Meow"
ElseIf Range("a2").Value = "Dog" Then
Range("b2").Value = "Woof"
ElseIf Range("a2").Value = "Duck" Then
Range("b2").Value = "Quack"
End If
End Sub
Now we will add an Else:
Else
The Else will run if no other previous conditions have been met.
We will finish our example by using an Else to indicate that if the cell value is not positive or negative, then it must be zero:
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
ElseIf Range("a2").Value < 0 Then
Range("b2").Value = "Negative"
Else
Range("b2").Value = "Zero"
End If
If-Else
The most common type of If statement is a simple If-Else:
Sub If_Else()
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
Else
Range("b2").Value = "Not Positive"
End If
End Sub
Nested IFs
You can also “nest” if statements inside of each other.
Sub Nested_Ifs()
If Range("a2").Value > 0 Then
Range("b2").Value = "Positive"
Else
If Range("a2").Value < 0 Then
Range("b2").Value = "Negative"
Else
Range("b2").Value = "Zero"
End If
End If
End Sub
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
IF – Or, And, Xor, Not
Next we will discuss the logical operators: Or, And, Xor, Not.
If Or
The Or operator tests if at least one condition is met.
The following code will test if the value in Range A2 is less than 5,000 or greater than 10,000:
If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Then
Range("b2").Value = "Out of Range"
End If
You can include multiple Ors in one line:
If Range("a2").Value < 5000 Or Range("a2").Value > 10000 Or Range("a2").Value = 9999 Then
Range("b2").Value = "Out of Range"
End If
If you are going to use multiple Ors, it’s recommended to use a line continuation character to make your code easier to read:
If Range("a2").Value < 5000 Or _
Range("a2").Value > 10000 Or _
Range("a2").Value = 9999 Then
Range("b2").Value = "Out of Range"
End If
If And
The And operator allows you to test if ALL conditions are met.
If Range("a2").Value >= 5000 And Range("a2").Value <= 10000 Then
Range("b2").Value = "In Range"
End If
VBA Programming | Code Generator does work for you!
If Xor
The Xor operator allows you to test if exactly one condition is met. If zero conditions are met Xor will return FALSE, If two or more conditions are met, Xor will also return false.
I’ve rarely seen Xor used in VBA programming.
If Not
The Not operator is used to convert FALSE to TRUE or TRUE To FALSE:
Sub IF_Not()
MsgBox Not (True)
End Sub
Notice that the Not operator requires parenthesis surrounding the expression to switch.
The Not operator can also be applied to If statements:
If Not (Range("a2").Value >= 5000 And Range("a2").Value <= 10000) Then
Range("b2").Value = "Out of Range"
End If
If Comparisons
When making comparisons, you will usually use one of the comparison operators:
Comparison Operator | Explanation |
---|---|
= | Equal to |
<> | Not Equal to |
> | Greater than |
>= | Greater than or Equal to |
< | Less than |
<= | Less than or Equal to |
However, you can also use any expression or function that results in TRUE or FALSE
If – Boolean Function
When build expressions for If Statements, you can also use any function that generates TRUE or False. VBA has a few of these functions:
Function | Description |
---|---|
IsDate | Returns TRUE if expression is a valid date |
IsEmpty | Check for blank cells or undefined variables |
IsError | Check for error values |
IsNull | Check for NULL Value |
IsNumeric | Check for numeric value |
They can be called like this:
If IsEmpty(Range("A1").Value) Then MsgBox "Cell Empty"
Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:
If Application.WorksheetFunction.IsText(Range("a2").Value) Then _
MsgBox "Cell is Text"
You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:
Sub If_Function()
If TrueFunction Then
MsgBox "True"
End If
End Sub
Function TrueFunction() As Boolean
TrueFunction = True
End Function
Comparing Text
You can also compare text similar to comparing numbers:
Msgbox "a" = "b"
Msgbox "a" = "a"
When comparing text, you must be mindful of the “Case” (upper or lower). By default, VBA considers letters with different cases as non-matching. In other words, “A” <> “a”.
If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:
Option Compare Text
After making that declaration “A” = “a”:
Option Compare Text
Sub If_Text()
MsgBox "a" = "A"
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
VBA If Like
The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:
Dim strName as String
strName = "Mr. Charles"
If strName Like "Mr*" Then
MsgBox "True"
Else
MsgBox "False"
End If
Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters. So the above If statement will return TRUE. The Like operator is an extremely powerful, but often under-used tool for dealing with text.
If Loops
VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.
Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:
Sub If_Loop()
Dim Cell as Range
For Each Cell In Range("A2:A6")
If Cell.Value > 0 Then
Cell.Offset(0, 1).Value = "Positive"
ElseIf Cell.Value < 0 Then
Cell.Offset(0, 1).Value = "Negative"
Else
Cell.Offset(0, 1).Value = "Zero"
End If
Next Cell
End Sub
If Else Examples
Now we will go over some more specific examples.
Check if Cell is Empty
This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:
Sub If_Cell_Empty()
If Range("a2").Value <> "" Then
Range("b2").Value = Range("a2").Value
End If
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Check if Cell Contains Specific Text
The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:
If Instr(Range("A2").value,"text") > 0 Then
Msgbox "Text Found"
End If
Check if cell contains text
This code will test if a cell is text:
Sub If_Cell_Is_Text()
If Application.WorksheetFunction.IsText(Range("a2").Value) Then
MsgBox "Cell is Text"
End If
End Sub
If Goto
You can use the result of an If statement to “Go to” another section of code.
Sub IfGoTo ()
If IsError(Cell.value) Then
Goto Skip
End If
'Some Code
Skip:
End Sub
Delete Row if Cell is Blank
Using Ifs and loops you can test if a cell is blank and if so delete the entire row.
Sub DeleteRowIfCellBlank()
Dim Cell As Range
For Each Cell In Range("A2:A10")
If Cell.Value = "" Then Cell.EntireRow.Delete
Next Cell
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
If MessageBox Yes / No
With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No. You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.
Here is the Yes/No Message Box in practice:
Sub MsgBoxVariable()
Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)
If answer = vbYes Then
MsgBox "Yes"
Else
MsgBox "No"
End If
End Sub
VBA If, ElseIf, Else in Access VBA
The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.
You can use an If statement to check if there are records in a Recordset.
When build expressions for If Statements, you can also use any function that generates TRUE or False. VBA has a few of these functions:
Function | Description |
---|---|
IsDate | Returns TRUE if expression is a valid date |
IsEmpty | Check for blank cells or undefined variables |
IsError | Check for error values |
IsNull | Check for NULL Value |
IsNumeric | Check for numeric value |
They can be called like this:
Excel also has many additional functions that can be called using WorksheetFunction. Here’s an example of the Excel IsText Function:
You can also create your own User Defined Functions (UDFs). Below we will create a simple Boolean function that returns TRUE. Then we will call that function in our If statement:
Comparing Text
You can also compare text similar to comparing numbers:
When comparing text, you must be mindful of the “Case” (upper or lower). By default, VBA considers letters with different cases as non-matching. In other words, “A” <> “a”.
If you’d like VBA to ignore case, you must add the Option Compare Text declaration to the top of your module:
After making that declaration “A” = “a”:
VBA If Like
The VBA Like Operator allows you to make inexact comparisons of text. Click the “Like Operator” link to learn more, but we will show a basic example below:
Here we’re using an asterisk “*” wildcard. The * stands for any number of any characters. So the above If statement will return TRUE. The Like operator is an extremely powerful, but often under-used tool for dealing with text.
If Loops
VBA Loops allow you to repeat actions. Combining IF-ELSEs with Loops is a great way to quickly process many calculations.
Continuing with our Positive / Negative example, we will add a For Each Loop to loop through a range of cells:
If Else Examples
Now we will go over some more specific examples.
Check if Cell is Empty
This code will check if a cell is empty. If it’s empty it will ignore the cell. If it’s not empty it will output the cell value to the cell to the right:
Check if Cell Contains Specific Text
The Instr Function tests if a string of text is found in another string. Use it with an If statement to check if a cell contains specific text:
Check if cell contains text
This code will test if a cell is text:
If Goto
You can use the result of an If statement to “Go to” another section of code.
Delete Row if Cell is Blank
If MessageBox Yes / No
With VBA Message Boxes you’re able to ask the user to select from several options. The Yes/No Message Box asks the user to select Yes or No. You can add a Yes / No Message Box to a procedure to ask the user if they would like to continue running the procedure or not. You handle the user’s input using an If statement.
Here is the Yes/No Message Box in practice:
VBA If, ElseIf, Else in Access VBA
The If, ElseIf and Else functions work exactly the same in Access VBA as in Excel VBA.
You can use an If statement to check if there are records in a Recordset.
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Logical Operators: AND, OR, NOT, IF NOT in Excel VBA
Updated January 20, 2023
Excel VBA Logical Operators
Let’s say you want to process a customer order. For that, you want to first check to see if the ordered product exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in handy in such cases. Logical operators are used to evaluate more than one condition.
The main Excel VBA logical operators AND, OR, NOT are listed in the table below:
S/N | Operator | Description | Example | Output |
---|---|---|---|---|
1 | AND | AND: This is used to combine more than one condition. If all the conditions are true, AND evaluates to true. If any of the condition is false, AND evaluates to false | If true = true AND false = true THEN | false |
2 | OR | OR: This is used to combine more than one condition. If any of the conditions evaluate to true, OR returns true. If all of them are false, OR returns false | If true = true OR true = false THEN | true |
3 | NOT | NOT: This one works like an inverse function. If the condition is true, it returns false, and if a condition is false, it returns true. | If NOT (true) Then | false |
VBA Logical Operators Example Source Code
For the sake of simplicity, we will be comparing hard coded numbers.
Add ActiveX buttons to the sheet from the “Insert option.”
Set the properties as shown in the image below
VBA Logical Operators
The following table shows the properties that you need to change and the values that you need to update too.
Источник
VBA IF OR
IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.
IF OR Function in VBA
Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.
Table of contents
You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)
How to Use IF with OR Function in VBA?
We will show you a simple example of using the IF OR function in VBA.
A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.
Now, look at the syntax of the IF OR function in VBA.
It is the same as we saw in the worksheet example. For a better understanding, look at the below example.
We have the previous month’s price, the last 6-month average price, and the current monthly price here.
To decide whether to buy the product, we need to do some tests here, and those tests are.
If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”
Step 1: Open the IF condition inside the Sub procedure.
Code:
Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value
Step 3: The first logical condition completes. Now, open OR statement.
Code:
Step 4: Now, apply the second logical condition as Range(“D2”).Value
Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”
Code:
Step 6: In the next line, write what the result should be if the logical test Logical Test A logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test. read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.
Code:
Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.
Code:
Step 8: Close the IF statement with “End If.”
Code:
We complete the coding part.
Let us run this code using F5 or manually through the run option and see the result in cell E2.
We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.
IF OR VBA Function with Loops (Advanced)
Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loops Use VBA Loops A VBA loop in excel is an instruction to run a code or repeat an action multiple times. read more .
We have added a few more lines for the above data set.
We need to use the For Next Loop here.
Just keep the current code as it is.
Declare the variable as an Integer.
Now, open For Next Loop from 2 to 9.
For example, Range (“D2”).Value should be Range (“D” & k).Value
Now, run the code. First, we should get the status in all the cells.
You can copy the code below.
Code:
Recommended Articles
This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –
Источник
Adblock
detector
This Excel tutorial explains how to use the Excel OR function (in VBA) with syntax and examples.
Description
The Microsoft Excel OR function returns TRUE if any of the conditions are TRUE. Otherwise, it returns FALSE.
The OR function is a built-in function in Excel that is categorized as a Logical Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Please read our OR function (WS) page if you are looking for the worksheet version of the OR function as it has a very different syntax.
Syntax
The syntax for the OR function in Microsoft Excel is:
condition1 Or condition2 [... Or condition_n] )
Parameters or Arguments
- condition1, condition2, … condition_n
- Expressions that you want to test that can either be TRUE or FALSE.
Returns
The OR function returns TRUE if any of the conditions are TRUE.
The OR function returns FALSE if all conditions are FALSE.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
The OR function with this syntax can only be used in VBA code in Microsoft Excel.
Let’s look at some Excel OR function examples and explore how to use the OR function in Excel VBA code.
This first example combines the OR function with the IF Statement in VBA:
If LWebsite = "TechOnTheNet.com" Or LCount > 25 Then LResult = "Great" Else LResult = "Fair" End If
This would set the LResult variable to the string value «Great» if either LWebsite was «TechOnTheNet.com» or LCount > 25. Otherwise, it would set the LResult variable to the string value «Fair».
You can use the OR function with the AND function in VBA, for example:
If (LWebsite = "TechOnTheNet.com" Or LWebsite = "CheckYourMath.com") And LPages <= 10 Then LBandwidth = "Low" Else LBandwidth = "High" End If
This would set the LBandwidth variable to the string value «Low» if LWebsite was either «TechOnTheNet.com» or «CheckYourMath.com» and LPages <= 10. Otherwise, it would set the LBandwidth variable to the string value «High».
VBA Logical Operators: AND, OR, NOT
Let’s say you want to process a customer order. For that, you want to first check to see if the ordered product exists or not. If it does, you also want to check if the quantity on hand is enough. Logical operators come in handy in such cases. Logical operators are used to evaluate more than one condition.
The main Excel VBA logical operators AND, OR, NOT are listed in the table below:
S/N | Operator | Description | Example | Output |
---|---|---|---|---|
1 | AND | AND: This is used to combine more than one condition. If all the conditions are true, AND evaluates to true. If any of the condition is false, AND evaluates to false | If true = true AND false = true THEN | false |
2 | OR | OR: This is used to combine more than one condition. If any of the conditions evaluate to true, OR returns true. If all of them are false, OR returns false | If true = true OR true = false THEN | true |
3 | NOT | NOT: This one works like an inverse function. If the condition is true, it returns false, and if a condition is false, it returns true. | If NOT (true) Then | false |
VBA Logical Operators Example Source Code
For the sake of simplicity, we will be comparing hard coded numbers.
Add ActiveX buttons to the sheet from the “Insert option.”
Set the properties as shown in the image below
The following table shows the properties that you need to change and the values that you need to update too.
S/N | Control | Property | Value |
---|---|---|---|
1 | CommandButton1 | Name | btnAND |
Caption | AND Operator (0 = 0) | ||
2 | CommandButton2 | Name | btnOR |
Caption | OR Operator (1 = 1) Or (5 = 0) | ||
3 | CommandButton3 | Name | btnNOT |
Caption | NOT Operator Not (0 = ) |
Add the following code to btnAND_Click
Private Sub btnAND_Click() If (1 = 1) And (0 = 0) Then MsgBox "AND evaluated to TRUE", vbOKOnly, "AND operator" Else MsgBox "AND evaluated to FALSE", vbOKOnly, "AND operator" End If End Sub
VBA If AND Operator
- “If (1 = 1) And (0 = 0) Then” the if statement uses the AND logical operator to combine two conditions (1 = 1) And (0 = 0). If both conditions are true, the code above ‘Else’ keyword is executed. If both conditions are not true, the code below ‘Else’ keyword is executed.
Add the following code to btnOR_Click
Private Sub btnOR_Click() If (1 = 1) Or (5 = 0) Then MsgBox "OR evaluated to TRUE", vbOKOnly, "OR operator" Else MsgBox "OR evaluated to FALSE", vbOKOnly, "OR operator" End If End Sub
VBA If OR Operator
- “If (1 = 1) Or (5 = 0) Then” the if statement uses the OR logical operator to combine two conditions (1 = 1) And (5 = 0). If any of the conditions is true, the code above Else keyword is executed. If both conditions are false, the code below Else keyword is executed.
Add the following code to btnNOT_Click
Private Sub btnNOT_Click() If Not (0 = 0) Then MsgBox "NOT evaluated to TRUE", vbOKOnly, "NOT operator" Else MsgBox "NOT evaluated to FALSE", vbOKOnly, "NOT operator" End If End Sub
VBA If NOT Operator
- “If Not (0 = 0) Then” the VBA If Not function uses the NOT logical operator to negate the result of the if statement condition. If the conditions is true, the code below ‘Else’ keyword is executed. If the condition is true, the code above Else keyword is executed.
Download Excel containing above code
In Excel VBA, IF Then Else statement allows you to check for a condition, and perform an action accordingly.
This is extremely valuable in many situations as we will see in the examples later in this tutorial.
To give you a simple example, suppose you have a list of grades in Excel and you want to highlight all those students who have scored an A. Now, if I ask you to do this manually, you will check each student’s grade and if it’s an A, you’ll highlight it, and if it isn’t, then you’ll leave it as is.
The same logic can be built in VBA using the If Then Else statement as well (and of course do a lot more than just highlighting grades).
In this tutorial, I’ll show you different ways the ‘If Then Else’ construct can be used in Excel VBA, and some practical examples in action.
But before I get into the specifics, let me give you the syntax of the ‘IF Then Else’ statement.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Syntax – IF Then Else
Below is the generic syntax of If Then Else construct in VBA
IF condition Then true_code [Else false_code]
Or
IF condition Then true_code Else false_code End IF
Note that the Else part of this statement is optional.
Now if you’re wondering what’s the difference between the two syntaxes, let me clarify.
The first syntax is a simple one-line IF THEN ELSE statement where you don’t need to use the END IF statement.
However, in the second syntax, the true_code part is in the second line. This is helpful when the code that you need to run in case the IF condition is true is long and consists of multiple lines.
When you split the IF statement into multiple lines, you need to tell VBA where the IF Then construct ends.
Hence you need to use the End IF statement.
In case you don’t use End IF when required, VBA will show you an error – “Block IF without END IF”
Examples of Using IF Then Statement in VBA
To give you an idea of how the IF-THEN statement works in VBA, let me start with some basic examples (some practical and more useful examples are covered later in this tutorial).
Suppose you have a student’s score in cell A1 and you want to check whether the student passed the exam or not (passing marks threshold being 35).
Then you can use the following code:
Sub CheckScore() If Range("A1").Value >=35 Then MsgBox "Pass" End Sub
The above code has a single line of IF statement that checks the value in cell A1.
If it’s more than 35, it shows the message – “Pass”.
If it’s less than 35, nothing happens.
But what if you want to show a message in both the cases, whether a student passed or failed the exam.
The below code would do this:
Sub CheckScore() If Range("A1").Value >= 35 Then MsgBox "Pass" Else MsgBox "Fail" End If End Sub
The above code uses the IF as well as the ELSE statement to execute two different conditions. When the score is more than (or equal to) 35, the IF condition is true, and the code right below it gets executed (everything before the Else statement).
But when the IF condition is FALSE, the code jumps to the Else part and executes the code block in it.
Note that when we use a single line of IF Then statement, we don’t need to use End IF. But when we split it into more than one line, we need to use the End If statement.
Nested IF Then (Multiple IF Then statements)
So far we have used a single IF Then statement.
In case you have multiple conditions to check, you can use:
- Multiple IF conditions
- If Then Else statement
- IF Then ElseIf Else construct
Let me show you how these differ and how to use this in Excel VBA.
Multiple IF Then Statements
Let’s take the same example of using a student’s score.
If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’.
We can use the below code to get this done:
Sub CheckScore() If Range("A1").Value < 35 Then MsgBox "Fail" If Range("A1").Value >= 35 Then MsgBox "Pass" End Sub
You can use multiple IF Then statement as shown above. While this works, it’s not an example of good coding (as you will see the alternatives below).
In case you decide to use this, remember that these statements should either be independent or mutually exclusive. The important thing to know here is that in the above construct, all the IF statements are evaluated and the ones where the condition is true, the code is executed.
So even if the first IF statement is correct, the second would still be evaluated.
IF Then Else Statement
Suppose this time, instead of just displaying the message Pass/Fail, we have one more condition.
If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.
We can use the below code to get this done:
Sub CheckScore() If Range("A1").Value < 35 Then MsgBox "Fail" Else If Range("A1").Value < 80 Then MsgBox "Pass" Else MsgBox "Pass, with Distinction" End If End If End Sub
In the above code, we have used multiple IF statements (nested IF Then) with the help of Else.
So there is an ‘IF Then Else’ construct within an ‘IF Then Else’ construct. This type of nesting allows you to check for multiple conditions and run the relevant block of code.
IF Then ElseIf Else Statement
The above code (that we saw in the previous section) can be further optimized by using the ElseIf statement.
Here is what we’re trying to do – If the student scores less than 35, the message to display is ‘Fail’, if the score is more than or equal to 35, the message to display is ‘Pass’, and if the score is more than 80, the message to display is ‘Pass, with Distinction’.
Sub CheckScore() If Range("A1").Value < 35 Then MsgBox "Fail" ElseIf Range("A1").Value < 80 Then MsgBox "Pass" Else MsgBox "Pass, with Distinction" End If End Sub
The above code uses ElseIf, which allows us to keep all the conditions within one single IF Then statement.
Using AND and OR in IF Then Else
So far in this tutorial, we have only checked for a single condition at a time.
However, when you have multiple dependent conditions, you can use the AND or OR statement with the IF conditions.
Below is the syntax of using AND/OR condition with the IF Then statement.
IF Condition1 AND Condition2 Then true_code Else false_code End IF
In the above code, only when both Condition1 and Condition2 are met, the true_code is executed. Even if one of the conditions is false, it will execute the false_code.
With OR, even if one of the conditions are true, it will execute the true_code. Only when all the conditions are false, it executes the false_code.
Now let’s see how AND and OR statement work with the IF Then Else construct.
Suppose you have the scores for two subjects instead of one, and you want to check for the following conditions:
- Fail – When the score is less than 35 in any of the subjects.
- Pass – When the score is more than or equal to 35, but less than 80 in both the subjects.
- Pass, with Distinction – When the score is more than 35 in both the subjects and is more than or equal to 80 in one or both the subjects.
Here is the code that will do this:
Sub CheckScore() If Range("A1").Value < 35 Or Range("B1").Value < 35 Then MsgBox "Fail" ElseIf Range("A1").Value < 80 And Range("B1").Value < 80 Then MsgBox "Pass" Else MsgBox "Pass, with Distinction" End If End Sub
The above code uses both OR and AND statements.
You can also write this same code with a slight change (using OR instead of AND).
Sub CheckScore() If Range("A1").Value < 35 Or Range("B1").Value < 35 Then MsgBox "Fail" ElseIf Range("A1").Value > 80 Or Range("B1").Value > 80 Then MsgBox "Pass, with Distinction" Else MsgBox "Pass" End If End Sub
Both the above VBA codes will give you the same result. Personally, I prefer the first one as it has a logical flow of checking the scores (but that’s just me).
Using Not Equal to in If Then
In all the examples above, we have used the conditions that check whether a value equal to a specified value or not.
You can also use similar codes when checking when the value is not equal to a specified value in the VBA code. Not equal to represented by <> the Excel VBA.
To see a practical example of using <>, have a look at Example 1 below.
Using If Then Else with Loops in VBA
So far, we have been going through some examples that are good to understand how the ‘IF-THEN’ statements work in VBA, however, are not useful in the practical world.
If I need to grade students, I can easily do that using Excel functions.
So let’s have a look at some useful and practical examples that can help you automate some stuff and be more efficient.
Example 1 – Save and Close All Workbooks Except The Active Workbook
If you have a lot of workbooks open and you quickly want to close all, except the active workbook, you can use the below code,
Sub SaveCloseAllWorkbooks() Dim wb As Workbook For Each wb In Workbooks On error resume next If wb.Name <> ActiveWorkbook.Name Then wb.Save wb.Close End If Next wb End Sub
The above code would save and close all the workbooks (except the active one).
It uses the For Next loop to go through the collection of all the open workbooks and checks the name using the IF condition.
If the name is not the same as that of the Active workbook, it saves and closes it.
In case there is a VBA code in any of the workbooks and you haven’t saved it as .xls or .xlsm, you will see a warning (as the vba codes are lost when you save it in .xlsx format).
Example 2 – Highlight Cells with Negative Values
Suppose that you have a column full of numbers and you want to quickly highlight all the cells with negative values in red, you can do that using the below code.
Sub HighlightNegativeCells() Dim Cll As Range For Each Cll In Selection If Cll.Value < 0 Then Cll.Interior.Color = vbRed Cll.Font.Color = vbWhite End If Next Cll End Sub
The above code uses the For Each loop and checks each cell in the selection that you have made. If the cell has a value that is negative, it’s highlighted in red with white font color.
Example 3 – Hide All the Worksheet Except the Current Worksheet
In case you want to quickly hide all the worksheets except the active one, you can use the below code:
Sub HideAllExceptActiveSheet() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets If ws.Name <> ActiveSheet.Name Then ws.Visible = xlSheetHidden Next ws End Sub
The above code uses the For Each loop to go through a collection of worksheets. It checks the name of each worksheet and hides it if it’s not the active worksheet.
Example 4 – Extract the Numeric Part from an Alphanumeric String
If you have alphanumeric strings in cells and you want to extract the numeric part from it, you can do that using the below code:
Function GetNumeric(CellRef As String) Dim StringLength As Integer StringLength = Len(CellRef) For i = 1 To StringLength If IsNumeric(Mid(CellRef, i, 1)) Then Result = Result & Mid(CellRef, i, 1) Next i GetNumeric = Result End Function
This code will create a custom function in Excel that can use within the worksheet (just like a regular function).
Where to Put the VBA Code?
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VB editor. You need to copy and paste the code in the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel Tutorials:
- How to Record a Macro in Excel.
- Working with Cells and Ranges in Excel VBA.
- Working with Worksheets in Excel VBA.
- Working with Workbooks in Excel VBA.
- Creating a Custom Function in Excel Using VBA.
- Excel VBA Events – An Easy (and Complete) Guide.
- Excel VBA MsgBox
- How to Run a Macro in Excel.
- How to Create and Use an Excel Add-in.
- Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
- Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
- How to Use Excel VBA InStr Function (with practical EXAMPLES).
IF is one of the most popular and frequently used statements in VBA. IF statement in VBA is sometimes also called as IF THEN ELSE Statement. The task of the IF Statement is to check if a particular condition is met or not.
If you have followed my earlier posts, then you would remember that we discussed If Function in Excel. The IF Function in Excel and the IF Statement in VBA are basically designed to do the same tasks, but the way they work is slightly different from each other.
Excel IF function checks a particular condition and if the condition is TRUE, it returns one value otherwise it returns the second value.
On the other hand, VBA IF Statement checks a condition but it doesn’t return any value. If the condition evaluates to TRUE then, it simply takes the program control to the instructions inside the IF block and starts executing them sequentially. However, if the condition evaluates to FALSE then it takes the program control to the statements inside the Else Block.
Although, it is not mandatory to have an Else Block with every IF statement. In such a case, if the condition inside IF statement evaluates to FALSE then the program control just moves to the next instruction (the instruction after the IF Block) and starts executing them sequentially.
Recommended Reading: Nested IF’s in Excel
Syntax of VBA IF Statement
Now let’s see the syntax of the IF statement in VBA:
IF condition_1 THEN
'Instructions inside First IF Block
ELSEIF condition_2 Then
'Instructions inside ELSEIF Block
...
ELSEIF condition_n Then
'Instructions inside nth ELSEIF Block
ELSE
'Instructions inside Else Block
END IF
Here, ‘condition_1
’ to ‘condition_n
’ refers to the expression that must evaluate to a Boolean value (i.e. either it should be TRUE or it should be FALSE).
The ‘THEN
’ keyword is basically a directive signifying that the instructions immediately following the IF Statement are to be executed if the condition evaluates to TRUE.
IF function usually ends with an ‘END IF
’ statement which tells the application that it is the last line of the IF function.
How VBA IF Statement Works
The conditions along with the IF Statements will be evaluated sequentially. This means, first of all, the IF Statement with ‘condition_1
’ will be evaluated, if it evaluates to TRUE then statements inside the first IF block will be executed and the rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped.
But, if the First IF Statement evaluates to FALSE then the ELSEIF statement following it will be evaluated. If it evaluates to TRUE then the instructions inside the ELSEIF Block will be sequentially executed and the rest of the blocks (ELSEIF’s and ELSE blocks) will be skipped.
However, in case, it also evaluates to FALSE then the next ELSEIF statement will be evaluated and so on. Finally, if all the IF and ELSEIF’s evaluate to FALSE then the ELSE block will be executed.
Note: Remember that out of IF, ELSEIF’s, and ELSE code blocks; only a single code block will be executed at a time based on the condition.
How to Use IF Statement in VBA
Now let’s understand how to use the IF Statement in VBA.
Before preceding let’s make our objective very clear.
Objective: Here we will generate a random number between 1-10 and then our task is to identify if the generated number is less than 5, equal to 5 or greater than 5.
So, we will try to write a VBA program as:
Sub IF_Test()
Dim num As Integer
num = WorksheetFunction.RandBetween(1, 10)
If num > 5 Then
MsgBox num & " is greater than 5"
ElseIf num = 5 Then
MsgBox num & " is equal to 5"
Else
MsgBox num & " is less than 5"
End If
End Sub
Explanation: In the above code we have used the RandBetween function of Excel to generate any random number from 1 – 10. After this, we have used an IF statement to check whether this number is greater than 5, equal to 5, or less than 5.
Based on the generated number, any one of the three conditions will evaluate to TRUE, and a suitable message box will pop out.
How this code works in three conditions:
If the Random number is greater than 5: Let’s consider the random number generated is 7. The program starts from Line-1 and executes all the instructions sequentially till Line-4. When it reaches Line-4 it checks ‘If 7 > 5
’, which is TRUE. So, it jumps to the instruction immediately beneath it and pops up a message saying “7 is greater than 5
”. After this, it directly jumps to the Line-10 and comes out of the whole IF Statement.
If the Random number is equal to 5: Let’s consider the random number generated is 5. In this case, when the program control reaches Line-4, it checks ‘If 5 > 5
’, which is FALSE. So, it skips the IF Block and jumps to the ELSEIF statement, here it checks ‘If 5 = 5
’ which evaluates to TRUE. So, it pops up a message saying “5 is equal to 5
”. (I know it’s a weird message, but I just used it for helping you to understand the things.)
After this, the program control directly jumps to Line-10, skips the ELSE part, and comes out of the whole IF statement.
If the Random number is less than 5: Let’s consider the random number generated is 3. So, In this case, when the program control reaches Line-4 it checks ‘If 3 > 5
’, which is FALSE. So, it skips the IF Block and jumps to the ELSEIF block, here it checks ‘If 3 = 5
’, which also evaluates to FALSE.
Now, as the above two blocks have evaluated to FALSE hence the ELSE block will be executed and pops out a message saying “3 is less than 5
”. Later the program control jumps to Line-10 and ends the IF Statement.
Examples of VBA IF Statement
Now, let’s move to some examples of the IF Statement in VBA.
Example 1: Using less than ‘<‘ operator with the VBA IF Function
Write a program to check whether the number entered by the user is negative or not.
Below VBA code can accomplish this:
Sub Find_Negative()
On Error GoTo catch_error
Dim number As Integer
number = InputBox("Enter the number: ")
If number < 0 Then
MsgBox "Entered number is negative!"
Else
MsgBox "Entered number is positive!"
End If
Exit Sub
catch_error:
MsgBox "Oops, Some Error Occurred !"
End Sub
Explanation:
In this code, first of all, we are accepting input numbers from the user. And then we check whether that number is greater than zero or not. If the number is less than zero, then IF block is executed and a message is displayed to the user saying, “Entered number is negative!
”.
But however, if the entered number is greater than zero then the program jumps to the Else block where it displays a message to the user saying, “Entered number is positive!
”.
Example 2: Using less than ‘=’ operator with the VBA IF Function
Write a VBA code to tell if the number entered by the user is Even or Odd.
Below is the code to do this:
Sub Find_Even_Odd()
On Error GoTo catch_error
Dim number As Integer
number = InputBox("Enter the number: ")
If number Mod 2 = 0 Then
MsgBox "Entered number is Even!"
Else
MsgBox "Entered number is Odd!"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub
Explanation:
In this code, just like the previous example first of all we are accepting input numbers from the user. And then we check whether the Modulus of that number with 2 is zero or not. If the Modulus is zero that means the number is divisible by 2 and hence is Even.
But however, if the modulus result is non-zero that means the number is not perfectly divisible by 2 and hence it is Odd.
Example 3: Using other functions within the VBA IF Function
Write a program to check if the string entered by the user is Palindrome or not.
A Palindrome string is that which reads the same forward as it does backward for example level, civic, etc.
Below is the code to accomplish this task:
Sub Check_Palindrome()
On Error GoTo catch_error
Dim word As String
Dim Rev_Word As String
word = InputBox("Enter the string ")
Rev_Word = StrReverse(word)
If LCase(word) = LCase(Rev_Word) Then
MsgBox "Entered String is Palindrome !"
Else
MsgBox "Entered String is non Palindrome !"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occured"
End Sub
Explanation:
The logic of this code is quite simple, first of all, we have asked the user to enter a text sting. And then with the use of VBA StrReverse
a function (inbuilt function to reverse a text string), we have reversed the text string entered by the user.
Finally, we are matching both the strings i.e. user-entered string and reversed string in an IF statement to check whether both of them are the same or different. If both are the same that means the entered string is a palindrome.
Using IF statement with And & Or operators:
Logical operators make it possible for you to check multiple conditions at a time, inside a single IF statement. There are many logical operators in VBA like: And
, Or
, Not
, AndAlso
, OrElse
, and Xor
but in most cases, we only deal with the first three.
Note: All the above-mentioned operators are binary (i.e. they accept at least two operands) except NOT
. NOT
is unary because it takes a single operand.
Now, let’s have a look at their truth tables:
Condition | NOT Result |
---|---|
True | False |
False | True |
After seeing the above truth table you can clearly see that Not just returns the opposite logic of the condition.
Condition1 | Condition2 | AND Result | OR Result |
---|---|---|---|
True | True | True | True |
True | False | False | True |
False | True | False | True |
False | False | False | False |
See that AND only returns a TRUE value if both the conditions are TRUE. While OR returns TRUE if at-least any one of the two conditions is TRUE.
Now, let’s have a look at some examples of Logical Operators with IF Statement:
Example 4: Using OR Logical Operator With IF Statement in VBA
Write a program to ask the user his favorite color. If the color entered by the user is ‘White’ or ‘Black’, then display a message to tell him that you like the same color.
Below is the code to do this:
Sub Fav_Color()
On Error GoTo catch_error
Dim color As String
color = InputBox("Enter your favorite color: ")
If LCase(color) = "white" Or LCase(color) = "black" Then
MsgBox "Oh Really! I too like the same."
Else
MsgBox "Nice Choice"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub
See how I have used Or operator to check the combination of multiple conditions in my program.
Example 5: Using AND Logical Operator With IF Statement in VBA
In the below table we have a Grade Table. Our task is to write a program that accepts Marks from user and displays the corresponding Grade.
Below is the code to accomplish this:
Sub Grade_Marks()
On Error GoTo catch_error
Dim Marks As Integer
Marks = InputBox("Enter your marks: ")
If Marks <= 100 And Marks >= 85 Then
MsgBox "Grade A"
ElseIf Marks < 85 And Marks >= 75 Then
MsgBox "Grade B"
ElseIf Marks < 75 And Marks >= 65 Then
MsgBox "Grade C"
ElseIf Marks < 65 And Marks >= 55 Then
MsgBox "Grade D"
ElseIf Marks < 55 And Marks >= 45 Then
MsgBox "Grade E"
ElseIf Marks < 45 Then
MsgBox "Fail"
End If
Exit Sub
catch_error:
MsgBox "Some Error Occurred"
End Sub
In this code see how I have used the AND operator to produce the required conditions.
Note: As a better coding practice it is always nice to use Select Case statements instead of writing multiple ELSEIF statements (just like we have seen in the above example). Select Case statements to execute faster and look cleaner than IF THEN ELSE.
Recommend Reading: Select Case Statement
So, this was all about VBA IF Statement. Do read this post if this long article has bored you and don’t forget to share your ideas and thoughts with us in the comments section.
Excel VBA OR Function
Like a worksheet function excel VBA also has a logical function which is OR function. In any programming language OR function is defined as follows:
Condition 1 OR Condition 2. If any of the given conditions happens to be true the value returned by the function is true while if both of the condition happens to be false the value returned by the function is false. OR Function can be termed as that it is opposite to AND function because in AND function both of the condition needs to be true in order to get a true value. Even if a single condition is termed as false then the whole value returned by the AND function is false. While in OR Function only one condition needs to be true in order to get TRUE as an output.
Syntax of OR Function in Excel VBA
VBA OR function has the following syntax:
{Condition 1} OR {Condition 2}
Let us use this function in VBA to have a clear mindset of how to use this function in general terms.
Note: In order to use VBA we need to have developer access enabled from the file tab.
How to Use Excel VBA OR Function?
We will learn how to use VBA OR Function with few examples in excel.
You can download this VBA OR Excel Template here – VBA OR Excel Template
Example #1 – VBA OR
To use this OR Function in our first example let us assume that there are four values A, B, C and D. We will assign these variables certain Values and check that if A>B or C>D and if any of the conditions is true what we will get as an output.
Follow the below steps to use VBA Union function in Excel:
Step 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.
Step 2: A code window will appear on the right-hand side of the screen. Define the subfunction as Sample.
Code:
Sub Sample() End Sub
Step 3: Define the four variables A B C and D as integers.
Code:
Sub Sample() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer End Sub
Step 4: Define a variable X to store the value of OR Function, define it as a string.
Code:
Sub Sample() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String End Sub
Step 5: Assign Random Values to A B C and D.
Code:
Sub Sample() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String A = 10 B = 15 C = 20 D = 25 End Sub
Step 6: Define X’s Values as conditions for A B C and D.
Code:
Sub Sample() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String A = 10 B = 15 C = 20 D = 25 X = A > B Or C > D End Sub
Step 7: Now we will display the value of X stored in it.
Code:
Sub Sample() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String A = 10 B = 15 C = 20 D = 25 X = A > B Or C > D MsgBox X End Sub
Step 8: Run the code from the run button provided in the screenshot below and then we see the following result when we run the above code.
Why we get the value as false because A is not greater than B and C is not greater than D. Both of the values of the condition were returned as false so our final output is also returned as false.
Example #2 – VBA OR
Now let us interchange the values for X from example 1. I mean to say that this time our expression for X will be A<B OR C>D. And we will see what will be the result displayed by the code.
Step 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.
Step 2: A code window will appear on the right-hand side of the screen. Define the subfunction as Sample1.
Code:
Sub Sample1() End Sub
Step 3: Define the four variables A B C and D as integers.
Code:
Sub Sample1() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer End Sub
Step 4: Define a variable X to store the value of OR Function, define it as a string.
Code:
Sub Sample1() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String End Sub
Step 5: Assign Random Values to A B C and D.
Code:
Sub Sample1() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String A = 10 B = 15 C = 20 D = 25 End Sub
Step 6: Define X’s Values as conditions for A B C and D.
Code:
Sub Sample1() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String A = 10 B = 15 C = 20 D = 25 X = A < B Or C > D End Sub
Step 7: Now we will display the value of X stored in it.
Code:
Sub Sample1() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim X As String A = 10 B = 15 C = 20 D = 25 X = A < B Or C > D MsgBox X End Sub
Step 8: Run the code above from the run button as shown and we will see the following result as we run the above code.
Why we get the value as True because A is less than B and C is not greater than D. One of the values of the condition were returned as true so our final output is also returned as true.
Example #3 – VBA OR
Now let us use OR Function in VBA with the IF function. Earlier we used another variable to store the Boolean value of OR function and display it. This time we will use a personalized message to display using or and if function.
Steps 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.
Step 2: A code window will appear on the right-hand side of the screen. Define the subfunction as Sample2.
Code:
Sub Sample2() End Sub
Step 3: Define all the four variables A B C and D as integers and assign them random values.
Code:
Sub Sample2() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer A = 5 B = 10 C = 15 D = 20 End Sub
Step 4: Now write the if statement for the given variables, for example, like in the code given below,
Code:
Sub Sample2() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer A = 5 B = 10 C = 15 D = 20 If (A < B) Or (C > D) Then End Sub
Step 5: Write a personalized message if any of the logical conditions is true or even if it is false.
Code:
Sub Sample2() Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer A = 5 B = 10 C = 15 D = 20 If (A < B) Or (C > D) Then MsgBox "One of the conditions is true" Else MsgBox "None of the conditions is true" End If End Sub
Step 6: Run the above code from the run button and we will get the following result displayed.
As one of the conditions were true we have the above result.
Example #4 – VBA OR
Let use VBA OR function in a real scenario. We have the following data, Name of the employees and sales done by them. If their sales are equals to specific criteria or greater than that then they will receive the incentive or there will be no incentive for those employees. Have a look at the data below,
The incentive criteria are 10000 for this example. If the sales done by the employees is equals to or above 10000 they will receive the incentive.
Steps 1: Now once we are in VB Editor go ahead and insert a new module from the insert section.
Step 2: In the code window, declare the subfunction,
Code:
Sub Employee() End Sub
Step 3: Declare a variable X as Long and write the if statement as below,
Code:
Sub Employee() Dim X As Long For X = 2 To 10 If Cells(X, 2).Value = 10000 Or Cells(X, 2).Value > 10000 Then Cells(X, 3).Value = "Incentive" Else Cells(X, 3).Value = "No Incentive" End If End Sub
Step 4: Start the loop for the next cell.
Code:
Sub Employee() Dim X As Long For X = 2 To 10 If Cells(X, 2).Value = 10000 Or Cells(X, 2).Value > 10000 Then Cells(X, 3).Value = "Incentive" Else Cells(X, 3).Value = "No Incentive" End If Next X End Sub
Step 5: Run the code to form the run button provided and once we have run the code check the result below,
In the If Statement, we used that if the sales are done is equals to 10000 or sales done greater than 10000 the employee will receive incentive.
Things to Remember
There are a few things we need to remember about VBA OR Function:
- It is a logical function in excel or any other programming language.
- It returns a logical output true or false.
- It is the opposite of AND Function.
Recommended Articles
This is a guide to VBA OR. Here we have discussed how to use Excel VBA OR Function along with practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA On Error
- VBA Number Format
- VBA VLOOKUP
- VBA Function