Using if and or in excel macro

The IF function allows you to make a logical comparison between a value and what you expect by testing for a condition and returning a result if that condition is True or False.

  • =IF(Something is True, then do something, otherwise do something else)

But what if you need to test multiple conditions, where let’s say all conditions need to be True or False (AND), or only one condition needs to be True or False (OR), or if you want to check if a condition does NOT meet your criteria? All 3 functions can be used on their own, but it’s much more common to see them paired with IF functions.

Use the IF function along with AND, OR and NOT to perform multiple evaluations if conditions are True or False.

Syntax

  • IF(AND()) — IF(AND(logical1, [logical2], …), value_if_true, [value_if_false]))

  • IF(OR()) — IF(OR(logical1, [logical2], …), value_if_true, [value_if_false]))

  • IF(NOT()) — IF(NOT(logical1), value_if_true, [value_if_false]))

Argument name

Description

logical_test (required)

The condition you want to test.

value_if_true (required)

The value that you want returned if the result of logical_test is TRUE.

value_if_false (optional)

The value that you want returned if the result of logical_test is FALSE.

Here are overviews of how to structure AND, OR and NOT functions individually. When you combine each one of them with an IF statement, they read like this:

  • AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False)

  • OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False)

  • NOT – =IF(NOT(Something is True), Value if True, Value if False)

Examples

Following are examples of some common nested IF(AND()), IF(OR()) and IF(NOT()) statements. The AND and OR functions can support up to 255 individual conditions, but it’s not good practice to use more than a few because complex, nested formulas can get very difficult to build, test and maintain. The NOT function only takes one condition.

Examples of using IF with AND, OR and NOT to evaluate numeric values and text

Here are the formulas spelled out according to their logic:

Formula

Description

=IF(AND(A2>0,B2<100),TRUE, FALSE)

IF A2 (25) is greater than 0, AND B2 (75) is less than 100, then return TRUE, otherwise return FALSE. In this case both conditions are true, so TRUE is returned.

=IF(AND(A3=»Red»,B3=»Green»),TRUE,FALSE)

If A3 (“Blue”) = “Red”, AND B3 (“Green”) equals “Green” then return TRUE, otherwise return FALSE. In this case only the first condition is true, so FALSE is returned.

=IF(OR(A4>0,B4<50),TRUE, FALSE)

IF A4 (25) is greater than 0, OR B4 (75) is less than 50, then return TRUE, otherwise return FALSE. In this case, only the first condition is TRUE, but since OR only requires one argument to be true the formula returns TRUE.

=IF(OR(A5=»Red»,B5=»Green»),TRUE,FALSE)

IF A5 (“Blue”) equals “Red”, OR B5 (“Green”) equals “Green” then return TRUE, otherwise return FALSE. In this case, the second argument is True, so the formula returns TRUE.

=IF(NOT(A6>50),TRUE,FALSE)

IF A6 (25) is NOT greater than 50, then return TRUE, otherwise return FALSE. In this case 25 is not greater than 50, so the formula returns TRUE.

=IF(NOT(A7=»Red»),TRUE,FALSE)

IF A7 (“Blue”) is NOT equal to “Red”, then return TRUE, otherwise return FALSE.

Note that all of the examples have a closing parenthesis after their respective conditions are entered. The remaining True/False arguments are then left as part of the outer IF statement. You can also substitute Text or Numeric values for the TRUE/FALSE values to be returned in the examples.

Here are some examples of using AND, OR and NOT to evaluate dates.

Examples of using IF with AND, OR and NOT to evaluate dates

Here are the formulas spelled out according to their logic:

Formula

Description

=IF(A2>B2,TRUE,FALSE)

IF A2 is greater than B2, return TRUE, otherwise return FALSE. 03/12/14 is greater than 01/01/14, so the formula returns TRUE.

=IF(AND(A3>B2,A3<C2),TRUE,FALSE)

IF A3 is greater than B2 AND A3 is less than C2, return TRUE, otherwise return FALSE. In this case both arguments are true, so the formula returns TRUE.

=IF(OR(A4>B2,A4<B2+60),TRUE,FALSE)

IF A4 is greater than B2 OR A4 is less than B2 + 60, return TRUE, otherwise return FALSE. In this case the first argument is true, but the second is false. Since OR only needs one of the arguments to be true, the formula returns TRUE. If you use the Evaluate Formula Wizard from the Formula tab you’ll see how Excel evaluates the formula.

=IF(NOT(A5>B2),TRUE,FALSE)

IF A5 is not greater than B2, then return TRUE, otherwise return FALSE. In this case, A5 is greater than B2, so the formula returns FALSE.

Example of the Evaluate Formula Wizard

Using AND, OR and NOT with Conditional Formatting

You can also use AND, OR and NOT to set Conditional Formatting criteria with the formula option. When you do this you can omit the IF function and use AND, OR and NOT on their own.

From the Home tab, click Conditional Formatting > New Rule. Next, select the “Use a formula to determine which cells to format” option, enter your formula and apply the format of your choice.

Conditional Formatting > Edit Rule dialog showing the Formula method

Using the earlier Dates example, here is what the formulas would be.

Example of using AND, OR and NOT as Conditional Formatting tests

Formula

Description

=A2>B2

If A2 is greater than B2, format the cell, otherwise do nothing.

=AND(A3>B2,A3<C2)

If A3 is greater than B2 AND A3 is less than C2, format the cell, otherwise do nothing.

=OR(A4>B2,A4<B2+60)

If A4 is greater than B2 OR A4 is less than B2 plus 60 (days), then format the cell, otherwise do nothing.

=NOT(A5>B2)

If A5 is NOT greater than B2, format the cell, otherwise do nothing. In this case A5 is greater than B2, so the result will return FALSE. If you were to change the formula to =NOT(B2>A5) it would return TRUE and the cell would be formatted.

Note: A common error is to enter your formula into Conditional Formatting without the equals sign (=). If you do this you’ll see that the Conditional Formatting dialog will add the equals sign and quotes to the formula — =»OR(A4>B2,A4<B2+60)», so you’ll need to remove the quotes before the formula will respond properly.

Need more help?

Connect with an expert. Learn from live instructors.​​​​​​​

See also

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Learn how to use nested functions in a formula

IF function

AND function

OR function

NOT function

Overview of formulas in Excel

How to avoid broken formulas

Detect errors in formulas

Keyboard shortcuts in Excel

Logical functions (reference)

Excel functions (alphabetical)

Excel functions (by category)

Return to VBA Code Examples

In this Article

  • IF…AND
  • IF…OR
  • IF NOT…

This article will demonstrate how to use the VBA If statement with And, Or and  Not.

When we us an IF statement in Excel VBA, the statement will execute a line of code if the condition you are testing is true.

  • We can use AND statement and OR statements in conjunction with IF statements to test for more than one condition and direct the code accordingly.
  • We can also use a NOT statement with an IF statement to check if the condition is NOT true – it basically is the inverse of the IF statement when used alone.

IF…AND

We can use the IF…AND combination of logical operators when we wish to test for more than one condition where all the conditions need to be true for the next line of code to execute.

For example, consider the following sheet:

vba if and

To check if the Profit is over $5,000, we can run the following macro:

Sub CheckProfit()
   If Range("C5") >= 10000 And Range("C6") < 5000 Then
      MsgBox "$5,000 profit achieved!"
   Else
      Msgbox "Profit not achieved!"
   End If
End Sub

This macro will check that the cell C5 is greater or equal to $10,000 AND check that the cell B6 is less than $5,000. If these conditions are BOTH true, it will show the message box.

vba if and msg

If we amend the macro to check if C5 is just greater than $10,000, then the profit would not be achieved!

vba if and else

IF…OR

We can use the IF…OR combination of logical operators when we wish to test for more than one condition where only one of the conditions needs to be true for the next line of code to execute.

The format for this is almost identical to the IF…AND example above.

Sub CheckProfit()
   If Range("C5") > 10000 Or Range("C6") < 5000 Then
      MsgBox "$5,000 profit achieved!"
   Else
      Msgbox "Profit not achieved!"
   End If
End Sub

However, with this macro, because we are using an IF …OR statement, only one of the conditions needs to be true.

vba if or

IF NOT…

IF..NOT  changes the IF statement around – it will check to see if the condition is NOT true rather than checking to see if the condition is true.

Sub CheckProfit() 
If NOT Range("C5")< 10000 Or Range("C6") < 5000 Then 
   MsgBox "$5,000 profit achieved!" 
Else 
   Msgbox "Profit not achieved!" 
End If 
End Sub

In this example above, the IF statement is checking to see if the value in C5 is NOT smaller than 10000.

Therefore this line of code:

IF Range("C5") > 10000

and this this line of code:

IF NOT Range("C5") < 10000

are testing for the same thing!

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

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

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

Понравилась статья? Поделить с друзьями:
  • Using if and or command in excel
  • Using if and not excel
  • Using if and in excel 2013
  • Using headings in word
  • Using excel to solve equations