Vba excel аналог функции или

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:

vba logical operators and

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:

vba logical operators or

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:

vba logical operators not

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:

vba logical operators xor

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!
vba save as

Learn More!

Операторы, использующиеся в 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 следующая:

  1. «Not» – логическое отрицание;
  2. «And» – логическое И;
  3. «Or» – логическое ИЛИ;
  4. «Xor» – логическое исключение;
  5. «Eqv» – логическая эквивалентность;
  6. «Imp» – логическая импликация.

totn Excel Functions


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

VBA OR Function

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.

VBA OR Example 1

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 Example 1-1

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.”

VBA OR Example 2

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.

VBA OR Example 2-1

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.

Case Study 3

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.

Case Study 3-1

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

VBA OR

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.

OR module 1

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

VBA OR Example 1.1

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

Excel VBA OR Example 1.2

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

VBA Example 1.3

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

Example 1.4

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

Example 1.5

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

Example 1.6

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.

VBA OR Example 1.7

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.

OR module 2

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

VBA OR Example 2.1

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

Excel VBA OR Example 2.2

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

Example 2.3

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

Example 2.4

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

Example 2.5

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

Example 2.6

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.

VBA OR Example 2.7

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.

OR module 3

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

VBA OR Example 3.1

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

VBA OR Example 3.2

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

Example 3.3

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

Example 3.4

Step 6: Run the above code from the run button and we will get the following result displayed.

VBA OR Example 3.5

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,

VBA OR Example 4

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.

OR module 4.1

Step 2: In the code window, declare the subfunction,

Code:

Sub Employee()

End Sub

VBA OR Example 4.2

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

VBA OR Example 4.3

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

VBA OR Example 4.4

Step 5: Run the code to form the run button provided and once we have run the code check the result below,

VBA OR Example 4.5

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 –

  1. VBA On Error
  2. VBA Number Format
  3. VBA VLOOKUP
  4. VBA Function

Logical operators are used for performing logical and asthmatic operations on a set of values or variables. The table depicts all the different types of logical operators supported by Excel:

Operator      Description

AND  

(LOGICAL AND)

If both the conditions are True, then the Expression is true.

Example:

Assume variable A holds 10 and variable B holds 0, then 

a<>0 AND b<>0 is False

OR

( Logical OR Operator)

If any of the two conditions are True, then the condition is true.

Example:

Assume variable A holds 10 and variable B holds 0, then 

a<>0 OR b<>0 is true.

NOT

( Logical NOT Operator)

Reverse the result. If a condition is true, then the Logical NOT operator will make false.

Example:

Assume variable A holds 10 and variable B holds 0, then 

NOT(a<>0 OR b<>0) is false.

XOR

( Logical XOR Operator)

It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True.

Example:

Assume variable A holds 10 and variable B holds 0, then 

(a<>0 XOR b<>0) is true

1. AND  (LOGICAL AND)

If both the conditions are True, then the Expression is true.

Example:

Assume variable A holds 20 and variable B holds 0, then a<>0 AND b<>0 is False

Program:

Private Sub Demo_Loop()

Dim a As Integer //Declaring variable

 a = 20

 Dim b As Integer  //Declaring variable

 b = 0

If a <> 0 And b <> 0 Then

MsgBox ("AND LOGICAL Operator Result is : True")

 Else

 MsgBox ("AND LOGICAL Operator Result is : False")

 End If

End Sub

Output:

AND LOGICAL Operator Result is : False

2. OR( Logical OR Operator)

If any of the two conditions are True, then the condition is true.

Example:

Assume variable A holds 20 and variable B holds 0, then a<>0 OR b<>0 is true.

Program:

Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
a = 20
Dim b As Integer  //Declaring variable
b = 0
If a <> 0 Or b <> 0 Then
MsgBox ("OR LOGICAL Operator Result is : True")
Else
MsgBox ("OR LOGICAL Operator Result is : False")
End If
End Sub

Output:

OR LOGICAL Operator Result is : True

3. NOT( Logical NOT Operator)

Reverse the result. If a condition is true, then the Logical NOT operator will make false.

Example:

Assume variable A holds 20 and variable B holds 0, then NOT(a<>0 OR b<>0) is false.

Program:

Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
a = 20
Dim b As Integer  //Declaring variable
b = 0
If a <> 0 Not b <> 0 Then
MsgBox ("NOT LOGICAL Operator Result is : True")
Else
MsgBox ("NOT LOGICAL Operator Result is : False")
End If
End Sub

Output:

NOT LOGICAL Operator Result is : False

4. XOR( Logical XOR Operator)

It is the combination of NOT and OR Operator. If one, and only one, of the expressions, evaluate to be True, the result is True.

Example:

Assume variable A holds 20 and variable B holds 0, then (a<>0 XOR b<>0) is true.

Program:

Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
a = 20
Dim b As Integer  //Declaring variable
b = 0
If a <> 0 Xor b <> 0 Then
MsgBox ("XOR LOGICAL Operator Result is : True")
Else
MsgBox ("XOR LOGICAL Operator Result is : False")
End If
End Sub

Output:

XOR LOGICAL Operator Result is : True

A Sample Program showing all the Operators is included below along with the outputs:

Program:

 Private Sub Demo_Loop()
Dim a As Integer //Declaring variable
  a = 20
  Dim b As Integer  //Declaring variable
  b = 0
     
  If a <> 0 And b <> 0 Then
     MsgBox ("AND LOGICAL Operator Result is : True")
  Else
     MsgBox ("AND LOGICAL Operator Result is : False")
  End If
  If a <> 0 Or b <> 0 Then
     MsgBox ("OR LOGICAL Operator Result is : True")
  Else
     MsgBox ("OR LOGICAL Operator Result is : False")
  End If
  If Not (a <> 0 Or b <> 0) Then
     MsgBox ("NOT LOGICAL Operator Result is : True")
  Else
     MsgBox ("NOT LOGICAL Operator Result is : False")
  End If
  If (a <> 0 Xor b <> 0) Then
     MsgBox ("XOR  LOGICAL Operator Result is : True")
  Else
     MsgBox ("XOR LOGICAL Operator Result is : False")
  End If
End Sub

Output:

AND LOGICAL Operator Result is : False
OR LOGICAL Operator Result is : True
NOT LOGICAL Operator Result is : False
XOR LOGICAL Operator Result is : True

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

VBA Logical Operators

VBA Logical Operators

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

Понравилась статья? Поделить с друзьями:
  • Vba excel аналог поиск
  • Vba excel активная ячейка это
  • Vba excel активная ячейка на листе
  • Vba excel xldown range
  • Vba excel worksheets события