Операторы, использующиеся в VBA Excel для отрицания и сравнения логических выражений. Синтаксис, принимаемые значения, приоритет логических операторов.
Оператор «Not»
«Not» – это оператор логического отрицания (инверсия), который возвращает True, если условие является ложным, и, наоборот, возвращает False, если условие является истинным.
Синтаксис:
Таблица значений:
Условие | Результат |
---|---|
True | False |
False | True |
Оператор «And»
«And» – это оператор логического умножения (логическое И, конъюнкция), который возвращает значение True, если оба условия являются истинными.
Синтаксис:
Результат = Условие1 And Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Оператор «Or»
«Or» – это оператор логического сложения (логическое ИЛИ, дизъюнкция), который возвращает значение True, если одно из двух условий является истинным, или оба условия являются истинными.
Синтаксис:
Результат = Условие1 Or Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Оператор «Xor»
«Xor» – это оператор логического исключения (исключающая дизъюнкция), который возвращает значение True, если только одно из двух условий является истинным.
Синтаксис:
Результат = Условие1 Xor Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | False |
True | False | True |
False | True | True |
False | False | False |
Оператор «Eqv»
«Eqv» – это оператор логической эквивалентности (тождество, равенство), который возвращает True, если оба условия имеют одинаковое значение.
Синтаксис:
Результат = Условие1 Eqv Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | True |
Оператор «Imp»
«Imp» – это оператор логической импликации, который возвращает значение False, если первое (левое) условие является истинным, а второе (правое) условие является ложным, в остальных случаях возвращает True.
Синтаксис:
Результат = Условие1 Imp Условие2 |
Таблица значений:
Условие1 | Условие2 | Результат |
---|---|---|
True | True | True |
True | False | False |
False | True | True |
False | False | True |
Приоритет логических операторов
Приоритет определяет очередность выполнения операторов в одном выражении. Очередность выполнения логических операторов в VBA Excel следующая:
- «Not» – логическое отрицание;
- «And» – логическое И;
- «Or» – логическое ИЛИ;
- «Xor» – логическое исключение;
- «Eqv» – логическая эквивалентность;
- «Imp» – логическая импликация.
In this Article
- Using the And Logical Operator
- Using the Or Logical Operator
- Using the Not Logical Operator
- Using the Xor Logical Operator
- Is Operator
- Like Operator
VBA allows you to use the logical operators And, Or, Not, Xor to compare values. The operators are considered “Boolean”, which means they return True or False as a result.
If you want to learn how to compare strings, click here: VBA Compare Strings – StrComp
If you want to learn how to use comparison operators, click here: VBA Comparison Operators – Not Equal to & More
Using the And Logical Operator
The And logical operator compares two or more conditions. If all the conditions are true, the operator will return True. If at least one of the conditions is not true, the operator will return False. Here is an example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 5
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA and intB are equal to 5. If this is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set values of intA and intB to 5:
intA = 5
intB = 5
After that, we use the And operator in the If statement to check if the values are equal to 5:
If intA = 5 And intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As both variables are equal to 5, the blnResult returns True:
Image 1. Using the And logical operator in VBA
Using the Or Logical Operator
The Or logical operator compares two or more conditions. If at least one of the conditions is true, it will return True. If none of the conditions are true, the operator will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if both intA is equal to 5. or intB is equal to 10. If any of these conditions is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Or intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 2. Using the Or logical operator in VBA
Using the Not Logical Operator
The Not logical operator checks one or more conditions. If the conditions are true, the operator returns False. Otherwise, it returns True. Here is the code for the example:
Dim intA As Integer
Dim blnResult As Boolean
intA = 5
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if the value of intA is not equal to 6. If intA is different than 6, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5:
intA = 5
After that, we use the Not operator in the If statement to check if the value of intA is different than 6:
If Not (intA = 6) Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5, the blnResult returns True:
Image 3. Using the Not logical operator in VBA
Using the Xor Logical Operator
The Xor logical operator compares two or more conditions. If exactly one of the conditions is true, it will return True. If none of the conditions are true, or more than one are true, it will return False. Here is the code for the example:
Dim intA As Integer
Dim intB As Integer
Dim blnResult As Boolean
intA = 5
intB = 10
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
In this example, we want to check if exactly one of the values (intA or IntB) are equal to 5. If only one condition is true, the value of Boolean blnResult will be True, otherwise, it will be False.
First, we set the value of intA to 5 and intB to 10:
intA = 5
intB = 10
After that, we use the Or operator in the If statement to check if any of the values is equal to 5:
If intA = 5 Xor intB = 5 Then
blnResult = True
Else
blnResult = False
End If
As intA value is 5 and intB is 10, the blnResult returns True:
Image 4. Using the Xor logical operator in VBA
Is Operator
The Is Operator tests if two object variables store the same object.
Let’s look at an example. Here we will assign two worksheets to worksheet objects rng1 and rng2, testing if the two worksheet objects store the same worksheet:
Sub CompareObjects()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")
If ws1 Is ws2 Then
MsgBox "Same WS"
Else
MsgBox "Different WSs"
End If
End Sub
Of course the worksheet objects are not the same, so “Different WSs” is returned.
Like Operator
The Like Operator can compare two strings for inexact matches. This example will test if a string starts with “Mr.”
Sub LikeDemo()
Dim strName As String
Dim blnResult As Boolean
strName = "Mr. Michael James"
If strName Like "Mr*" Then
blnResult = True
Else
blnResult = False
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!
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».
The OR function is a logical function in any of the programming languages. Similar to VBA, we have an OR function, as it is a logical function. The result given by this function is either “True” or “False.” This function is used for two or many conditions together. It gives us a “True” result when either of the conditions returns “True.”
What is OR Function in VBA?
In Excel, logical functions are the heart of daily formulas. Logical functions are there to conduct the logical test and result in Boolean data type, i.e., TRUE or FALSE. Some logical formulas in Excel are IF, IFERROR in excelThe IFERROR function in Excel checks a formula (or a cell) for errors and returns a specified value in place of the error.read more, ISERROR in excelISERROR is a logical function that determines whether or not the cells being referred to have an error. If an error is found, it returns TRUE; if no errors are found, it returns FALSE.read more, , AND, and OR Excel functions.
We hope you have used them quite often as a worksheet function. In VBA, too, we can use all of them, and in this article, we will explain the ways of using the “VBA OR” function.
What is the first thing that comes to mind when you think of the word “OR”?
In simple terms, “OR” means “either this or that.”
With the same idea, OR is a logical function that gives the result as TRUE if any of the logical tests is TRUE and gives FALSE if none of the logical tests are TRUE.
It works exactly the opposite of the VBA AND function. The AND function returns TRUE only if all the logical conditions are TRUE. If any of the conditions are not satisfied, we will get FALSE.
Table of contents
- What is OR Function in VBA?
- The formula of VBA OR Function
- Examples of Using OR Function in VBA
- VBA OR Function With IF Condition is Powerful
- Case Study to Solve
- 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 OR Function (wallstreetmojo.com)
The formula of VBA OR Function
Let me frame a syntax for you to understand the function.
[Logical Test] OR [Logical Test] OR [Logical Test]
First, we need to mention the logical test, then mention the word “OR,” and then mention the second logical test. If you wish to conduct a more logical test, mention the word OR after a logical test.
Of all the logical tests you do, if any of the tests are satisfied or true, then we will get the result as TRUE if none or satisfied, then the result is FALSE.
Examples of Using OR Function in VBA
We will show you a simple example of using the OR function in VBA.
You can download this VBA OR Excel Template here – VBA OR Excel Template
To understand the logical VBA function OR let us give you an example. Let us say we want to conduct the logical test of whether the number 25 is greater than 20 or the number 50 is less than 30.
Step 1: Create a macro name.
Step 2: Define the variable as a string.
Code:
Sub OR_Example1() Dim i As String End Sub
Step 3: Now, we will assign the value through the OR logical test for this variable.
Code:
Sub OR_Example1() Dim i As String i = End Sub
Step 4: Our first logical test is 25 >20.
Code:
Sub OR_Example1() Dim i As String i = 25 > 20 End Sub
Step 5: Now, after the first logical test, mention the word OR and enter the second logical test.
Code:
Sub OR_Example1() Dim i As String i = 25 > 20 Or 50 < 30 End Sub
Step 6: Now, VBA OR function tests whether the logical tests are TRUE or FALSE. Now assign the result of the variable to the VBA message box.
Code:
Sub OR_Example1() Dim i As String i = 25 > 20 Or 50 < 30 MsgBox i End Sub
Step 7: Run the Macro and what the result is.
We got the result as TRUE because out of the two logical testsA 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 we have provided, one test is TRUE, so the result is TRUE.
25 is greater than 20, and 50 is not less than 30. In this case, the first logical test is TRUE, but the second is FALSE. Because we have applied the VBA OR function, it needs any one of the conditions to be TRUE to get the result as TRUE.
Now, look at the code below.
Code:
Sub OR_Example1() Dim i As String i = 25 = 20 Or 50 = 30 MsgBox i End Sub
We have changed the logical test equations from > and < to equal (=) sign. Therefore, it will return FALSE as the result because 25 is not equal to 20, and 50 is not equal to 30.
VBA OR Function With IF Condition is Powerful
As we said, the OR function can return either TRUE or FALSE as a result, but with the other logical function, “IF,” we can manipulate results as per our needs.
Take the same logical tests from above. Again, the OR function has returned only TRUE or FALSE, but let us combine this OR with IF.
Step 1: Before conducting any test, open the function IF.
Code:
Sub OR_Example2() Dim i As String IF End Sub
Step 2: Now, conduct tests using the OR function.
Code:
Sub OR_Example2() Dim i As String IF 25 = 20 Or 50 = 30 End Sub
Step 3: Put the word “Then” and write the result. If the condition is TRUE, assign the value to the variable as “Condition is Satisfied.”
Code:
Sub OR_Example2() Dim i As String If 25 = 20 Or 50 = 30 Then i = "Condition is Satisfied" End Sub
Step 4: If the condition is FALSE, then we need a different result, so put the word “ELSE” and, in the next line, assign the value to the variable “what should be the result if the condition or logical test is FALSE.”
Code:
Sub OR_Example2() Dim i As String If 25 = 20 Or 50 = 30 Then i = "Condition is Satisfied" Else i = "Condition is not Satisfied" End Sub
Step 5: End the IF function with “End If.”
Code:
Sub OR_Example2() Dim i As String If 25 = 20 Or 50 = 30 Then i = "Condition is Satisfied" Else i = "Condition is not Satisfied" End If End Sub
Step 6: Assign the value of the variable result to the message box.
Code:
Sub OR_Example2() Dim i As String If 25 = 20 Or 50 = 30 Then i = "Condition is Satisfied" Else i = "Condition is not Satisfied" End If MsgBox i End Sub
Run the Macro. If the logical test is TRUE, we will get the result as “Condition is Satisfied,” or else we will get “Condition is not Satisfied.”
We got the result “Condition is not Satisfied” because both the logical tests are FALSE.
Now, we will change the logical tests.
Code:
Sub OR_Example2() Dim i As String If 25 > 20 Or 50 < 30 Then i = "Condition is Satisfied" Else i = "Condition is not Satisfied" End If MsgBox i End Sub
We will run the macro and see what the result is.
Like this, we can use one logical function with other logical functions to arrive at the results.
Solve the below case study to get used to logical functions.
Case Study to Solve
We have employee names and their respective departments.
If you have tried and not found the result, then you can refer below code to understand the logic.
Code:
Sub Bonus_Calculation() Dim i As Long For i = 2 To 10 If Cells(i, 2).Value = "Finance" Or Cells(i, 2).Value = "IT" Then Cells(i, 3).Value = 5000 Else Cells(i, 3).Value = 1000 End If Next i End Sub
If the employee is from “Finance” or “IT,” then they should get the bonus of “5000.” For other department employees, the bonus is “1000.”
Conduct the logical test and arrive at the results.
Recommended Articles
This article has been a guide to VBA OR Function. Here, we learn how to use OR Logical Operator in VBA along with some practical examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –
- IFERROR in VBA
- Excel VBA On Error Statement
- Excel OR Function
- VBA Month Function
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