Или vba excel примеры

Операторы, использующиеся в 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» – логическая импликация.

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!

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

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

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

  1. First, start the IF statement with the “IF” keyword.
  2. After that, specify the first condition that you want to test.
  3. Next, use the OR keyword to specify the second condition.
  4. 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

  • Excel VBA ИЛИ Функция

Excel VBA ИЛИ Функция

Как и функция рабочего листа, Excel VBA также имеет логическую функцию, которая является функцией ИЛИ. В любом языке программирования ИЛИ функция определяется следующим образом:

Условие 1 ИЛИ Условие 2. Если какое-либо из заданных условий оказывается истинным, значение, возвращаемое функцией, является истинным, тогда как, если оба условия оказываются ложными, значение, возвращаемое функцией, является ложным. ИЛИ Функция может быть названа так, как будто она противоположна функции И, потому что в функции И оба условия должны быть истинными, чтобы получить истинное значение. Даже если одно условие называется ложным, тогда все значение, возвращаемое функцией AND, является ложным. В то время как в функции OR только одно условие должно быть истинным, чтобы получить TRUE в качестве выхода.

Синтаксис функции OR в Excel VBA

Функция VBA OR имеет следующий синтаксис:

 (Условие 1) ИЛИ (Условие 2) 

Давайте использовать эту функцию в VBA, чтобы иметь четкое представление о том, как использовать эту функцию в общих чертах.

Примечание . Чтобы использовать VBA, нам нужно включить доступ разработчика на вкладке «Файл».

Как использовать функцию Excel VBA ИЛИ?

Мы научимся использовать функцию VBA OR с несколькими примерами в Excel.

Вы можете скачать этот шаблон VBA ИЛИ Excel здесь — Шаблон VBA ИЛИ Excel

Пример № 1 — VBA ИЛИ

Чтобы использовать эту функцию OR в нашем первом примере, давайте предположим, что есть четыре значения A, B, C и D. Мы присвоим этим переменным определенные значения и проверим, что если A> B или C> D и если какое-либо из условий правда, что мы получим в качестве выхода.

Чтобы использовать функцию VBA Union в Excel, выполните следующие действия:

Шаг 1: Теперь, как только мы окажемся в VB Editor, добавьте новый модуль из раздела вставки.

Шаг 2: В правой части экрана появится окно с кодом. Определите подфункцию как образец.

Код:

 Sub Sample () End Sub 

Шаг 3: Определите четыре переменные ABC и D как целые числа.

Код:

 Sub Sample () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число 

Шаг 4: Определите переменную X для хранения значения функции OR, определите ее как строку.

Код:

 Sub Sample () Dim A в виде целого числа Dim B в виде целого числа Dim C в виде целого числа Dim D в виде целого числа Dim X в виде конца строки 

Шаг 5: назначить случайные значения ABC и D.

Код:

 Sub Sample () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X как строка A = 10 B = 15 C = 20 D = 25 End Sub 

Шаг 6: Определите значения X как условия для ABC и D.

Код:

 Sub Sample () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X как строка A = 10 B = 15 C = 20 D = 25 X = A> B или C> D End Sub 

Шаг 7: Теперь мы отобразим значение X, хранящееся в нем.

Код:

 Sub Sample () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X в виде строки A = 10 B = 15 C = 20 D = 25 X = A> B или C> D MsgBox X End Sub 

Шаг 8: Запустите код с помощью кнопки запуска, представленной на снимке экрана ниже, и затем мы увидим следующий результат при запуске приведенного выше кода.

Почему мы получаем значение как ложное, потому что A не больше чем B, а C не больше чем D. Оба значения условия были возвращены как ложные, поэтому наш конечный результат также возвращается как ложный.

Пример № 2 — VBA ИЛИ

Теперь давайте поменяем значения для X из примера 1. Я хочу сказать, что на этот раз наше выражение для X будет A D. И мы увидим, какой будет результат, отображаемый кодом.

Шаг 1: Теперь, как только мы окажемся в VB Editor, добавьте новый модуль из раздела вставки.

Шаг 2: В правой части экрана появится окно с кодом. Определите подфункцию как Sample1.

Код:

 Sub Sample1 () End Sub 

Шаг 3: Определите четыре переменные ABC и D как целые числа.

Код:

 Sub Sample1 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число 

Шаг 4: Определите переменную X для хранения значения функции OR, определите ее как строку.

Код:

 Sub Sample1 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X как строка конец Sub 

Шаг 5: назначить случайные значения ABC и D.

Код:

 Sub Sample1 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X как строка A = 10 B = 15 C = 20 D = 25 End Sub 

Шаг 6: Определите значения X как условия для ABC и D.

Код:

 Sub Sample1 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X как строка A = 10 B = 15 C = 20 D = 25 X = A D End Sub 

Шаг 7: Теперь мы отобразим значение X, хранящееся в нем.

Код:

 Sub Sample1 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число Dim X как строка A = 10 B = 15 C = 20 D = 25 X = A D MsgBox X End Sub 

Шаг 8 : Запустите приведенный выше код с кнопки запуска, как показано, и мы увидим следующий результат при запуске приведенного выше кода.

Почему мы получаем значение как True, потому что A меньше, чем B, а C не больше, чем D. Одно из значений условия было возвращено как true, поэтому наш конечный результат также возвращается как true.

Пример № 3 — VBA ИЛИ

Теперь давайте используем функцию OR в VBA с функцией IF. Ранее мы использовали другую переменную для хранения логического значения функции OR и ее отображения. На этот раз мы будем использовать персонализированное сообщение для отображения с помощью или и если функция.

Шаги 1: Теперь, как только мы окажемся в VB Editor, добавьте новый модуль из раздела вставки.

Шаг 2: В правой части экрана появится окно с кодом. Определите подфункцию как Sample2.

Код:

 Sub Sample2 () End Sub 

Шаг 3: Определите все четыре переменные ABC и D как целые и присвойте им случайные значения.

Код:

 Sub Sample2 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число A = 5 B = 10 C = 15 D = 20 End Sub 

Шаг 4: Теперь напишите оператор if для заданных переменных, например, как в приведенном ниже коде,

Код:

 Sub Sample2 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число A = 5 B = 10 C = 15 D = 20 если (AD), тогда End Sub 

Шаг 5: Напишите персональное сообщение, если любое из логических условий верно или даже если оно ложно.

Код:

 Sub Sample2 () Dim A как целое число Dim B как целое число Dim C как целое число Dim D как целое число A = 5 B = 10 C = 15 D = 20 If (AD) Тогда MsgBox "Одно из условий истинно" Else MsgBox "Нет из условий верно "End If End Sub 

Шаг 6: Запустите приведенный выше код с кнопки запуска, и мы получим следующий результат.

Поскольку одно из условий было выполнено, мы имеем вышеуказанный результат.

Пример № 4 — VBA ИЛИ

Позвольте использовать функцию VBA OR в реальном сценарии. У нас есть следующие данные: ФИО сотрудников и выполненные ими продажи. Если их продажи равны определенным критериям или превышают их, тогда они получат стимул, или у этих сотрудников не будет стимула. Посмотрите на данные ниже,

Критерии стимулирования 10000 для этого примера. Если продажи, сделанные сотрудниками, равны или превышают 10000, они получат поощрение.

Шаги 1: Теперь, как только мы окажемся в VB Editor, добавьте новый модуль из раздела вставки.

Шаг 2: В окне кода объявите подфункцию,

Код:

 Sub Employee () End Sub 

Шаг 3: Объявите переменную X как Long и напишите оператор if, как показано ниже,

Код:

 Sub Employee () Dim X As Long Для X = от 2 до 10, если клетки (X, 2). Значение = 10000 или клетки (X, 2). Значение> 10000, затем клетки (X, 3). Значение = "Стимулирующее" Остальное Ячейки (X, 3) .Value = "Без стимула" End If End Sub 

Шаг 4: Запустите цикл для следующей ячейки.

Код:

 Sub Employee () Dim X As Long Для X = от 2 до 10, если клетки (X, 2). Значение = 10000 или клетки (X, 2). Значение> 10000, затем клетки (X, 3). Значение = "Стимулирующее" Остальное Ячейки (X, 3) .Value = "Нет стимула" End If Next X End Sub 

Шаг 5: Запустите код, чтобы сформировать предоставленную кнопку запуска, и как только мы запустим код, проверьте результат ниже,

В заявлении «Мы» мы указали, что если объем продаж равен 10000 или объем продаж превышает 10000, сотрудник получит вознаграждение.

То, что нужно запомнить

Есть несколько вещей, которые мы должны помнить о функции VBA OR:

  • Это логическая функция в Excel или любом другом языке программирования.
  • Возвращает логический вывод true или false.
  • Это противоположность функции AND.

Рекомендуемые статьи

Это руководство по VBA ИЛИ. Здесь мы обсудили, как использовать функцию Excel VBA OR вместе с практическими примерами и загружаемым шаблоном Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Полное руководство по VBA при ошибке
  2. Как использовать числовой формат VBA?
  3. VBA VLOOKUP Функция с примерами
  4. Создание функции VBA в Excel


Понравилась статья? Поделить с друзьями:
  • Иконки на кнопках excel
  • Иконки для файлов word
  • Иконки для текста word
  • Иконки для программы word
  • Иконки для документов word