Vba excel условие или

IF OR is not a single statement. Rather, these are two logical functions used together in VBA when we have more than one criteria to check. When we use the IF statement, if any criteria meet, we get the TRUE result. OR statement is used between the two criteria of the IF statement.

IF OR Function in VBA

Logical functions are the heart of any criteria-based calculations. The IF function is the most popular logical function, be it a worksheet function or a VBA function because it serves excellently for our needs. But one more logical function, OR in excel, is the most underrated. It is also important to master when it comes to solving complex calculations. This article will take you through the VBA IF OR function in detail. Read the full article to get the function in detail.

Table of contents
  • IF OR Function in VBA
    • How to Use IF with OR Function in VBA?
    • IF OR VBA Function with Loops (Advanced)
    • Recommended Articles

VBA IF OR

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA IF OR (wallstreetmojo.com)

How to Use IF with OR Function in VBA?

We will show you a simple example of using the IF OR function in VBA.

You can download this VBA IF OR Excel Template here – VBA IF OR Excel Template

A combination of logical functions is the best pair in Excel. However, combining many logical formulas inside the other logical formula suggests that calculation requires many conditions to test.

Now, look at the syntax of the IF OR function in VBA.

[Test] OR [Test] OR [Test]

It is the same as we saw in the worksheet example. For a better understanding, look at the below example.

VBA IF OR Example 1

We have the previous month’s price, the last 6-month average price, and the current monthly price here.

To decide whether to buy the product, we need to do some tests here, and those tests are.

If the Current Price is less than or equal to any of the other two prices, we should get the result as “Buy” or else should get the result as “Do Not Buy.”

Step 1: Open the IF condition inside the Sub procedure.

Code:

Sub IF_OR_Example1()

 If

End Sub

VBA IF OR Example 1-1

Step 2: Inside the IF condition, apply the first logical test as Range(“D2”).Value <= Range(“B2”).Value

Code:

Sub IF_OR_Example1()

 If Range(“D2”).Value <= Range(“B2”).Value

End Sub

VBA IF OR Example 1-2

Step 3: The first logical condition completes. Now, open OR statement.

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value OR

End Sub

VBA IF OR Example 1-3

Step 4: Now, apply the second logical condition as Range(“D2”).Value <= Range(“C2”).Value

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value OR Range("D2").Value <= Range("C2").Value

End Sub

VBA IF OR Example 1-4

Step 5: We are done with the logical tests here. After the logical tests, put the word “Then.”

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then

End Sub

VBA IF OR Example 1-5

Step 6: In the next line, write what the result should be if the logical testA logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more is TRUE. If the condition is TRUE, we need the result as “Buy” in cell E2.

Code:

Sub IF_OR_Example1()

 If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then  

    Range("E2").Value = "Buy"

End Sub

VBA IF OR Example 1-6

Step 7: If the result is FALSE, we should get the result as “Do Not Buy.” So in the next line, put “Else” and write the code in the next line.

Code:

Sub IF_OR_Example1()

If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then 

   Range("E2").Value = "Buy"
Else
   Range("E2").Value = "Do Not Buy"

End Sub

VBA IF OR Example 1-7

Step 8: Close the IF statement with “End If.”

Code:

Sub IF_OR_Example1()

If Range("D2").Value <= Range("B2").Value Or Range("D2").Value <= Range("C2").Value Then

   Range("E2").Value = "Buy"
Else
   Range("E2").Value = "Do Not Buy"
End If

End Sub

VBA IF OR Example 1-8

We complete the coding part.

Let us run this code using F5 or manually through the run option and see the result in cell E2.

Example 1-9

We got the result as “Buy” because the current monthly price of Apple is less than the price of both “Previous Month” as well as “6 Month Average Price”.

IF OR VBA Function with Loops (Advanced)

Once you understand the formula, try to use it with a larger number of cells. In the case of a larger number of cells, we cannot write any line of code, so we need to use VBA loopsA VBA loop in excel is an instruction to run a code or repeat an action multiple times.read more.

We have added a few more lines for the above data set.

Example 2

We need to use the For Next Loop here.

Just keep the current code as it is.

Declare the variable as an Integer.

Example 2-1

Now, open For Next Loop from 2 to 9.

Example 2-2

Now, wherever we have cell referenceCell reference in excel is referring the other cells to a cell to use its values or properties. For instance, if we have data in cell A2 and want to use that in cell A1, use =A2 in cell A1, and this will copy the A2 value in A1.read more, change the current number, and concatenate the variable “k” with them.

For example, Range (“D2”).Value should be Range (“D” & k).Value

Example 2-3

Now, run the code. First, we should get the status in all the cells.

Example 2-4

You can copy the code below.

Code:

Sub IF_OR_Example1()

Dim k As Integer

For k = 2 To 9

If Range("D" & k).Value <= Range("B" & k).Value Or Range("D" & k).Value <= Range("C" & k).Value Then

Range("E" & k).Value = "Buy"
Else

Range("E" & k).Value = "Do Not Buy"

End If

Next k

End Sub

Recommended Articles

This article has been a guide to VBA IF OR. Here, we learn how to use IF Condition with OR function in Excel VBA, examples, and downloadable templates. Below are some useful articles related to VBA: –

  • VBA INT
  • VBA LEN
  • VBA Integer
  • VBA MID Function

Home / VBA / VBA IF OR (Test Multiple Conditions)

You can use the OR operator with the VBA IF statement to test multiple conditions. When you use it, it allows you to test two or more conditions simultaneously and returns true if any of those conditions are true. But if all the conditions are false only then it returns false in the result.

Use OR with IF

  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

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

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 форма поиска
  • Vba excel условие если не ошибка
  • Vba excel форма на весь экран
  • Vba excel условие если в ячейке есть значение
  • Vba excel форма картинки