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.
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.
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. |
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.
Using the earlier Dates example, here is what the formulas would be.
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?
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)
Содержание
- Use AND and OR to test a combination of conditions
- Use AND and OR with IF
- Sample data
- Using IF with AND, OR and NOT functions
- Examples
- Using AND, OR and NOT with Conditional Formatting
- Need more help?
- See also
- IF, AND, OR, Nested IF & NOT Logical Functions in Excel
- What is a Logical Function?
- IF Function example
- Nested IF functions
- Practical example
- Summary
- Excel IF statement with multiple conditions
- How to use IF function with multiple conditions
- Excel IF statement with multiple conditions (AND logic)
- Excel IF function with multiple conditions (OR logic)
- IF with multiple AND & OR statements
- Nested IF statement to check multiple logical tests
- Excel IF array formula with multiple conditions
- Using IF together with other functions
- Example 1. If #N/A error in VLOOKUP
- Example 2. IF with SUM, AVERAGE, MIN and MAX functions
- Example 3. IF with ISNUMBER, ISTEXT and ISBLANK
- Example 4. IF and CONCATENATE
- IF ISERROR / ISNA formula in Excel
Use AND and OR to test a combination of conditions
When you need to find data that meets more than one condition, such as units sold between April and January, or units sold by Nancy, you can use the AND and OR functions together. Here’s an example:
This formula nests the AND function inside the OR function to search for units sold between April 1, 2011 and January 1, 2012, or any units sold by Nancy. You can see it returns True for units sold by Nancy, and also for units sold by Tim and Ed during the dates specified in the formula.
Here’s the formula in a form you can copy and paste. If you want to play with it in a sample workbook, see the end of this article.
Use AND and OR with IF
You can also use AND and OR with the IF function.
In this example, people don’t earn bonuses until they sell at least $125,000 worth of goods, unless they work in the southern region where the market is smaller. In that case, they qualify for a bonus after $100,000 in sales.
Let’s look a bit deeper. The IF function requires three pieces of data (arguments) to run properly. The first is a logical test, the second is the value you want to see if the test returns True, and the third is the value you want to see if the test returns False. In this example, the OR function and everything nested in it provides the logical test. You can read it as: Look for values greater than or equal to 125,000, unless the value in column C is «South», then look for a value greater than 100,000, and every time both conditions are true, multiply the value by 0.12, the commission amount. Otherwise, display the words «No bonus.»
Sample data
If you want to work with the examples in this article, copy the following table into cell A1 in your own spreadsheet. Be sure to select the whole table, including the heading row.
Источник
Using IF with AND, OR and NOT functions
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.
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]))
The condition you want to test.
The value that you want returned if the result of logical_test is TRUE.
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.
Here are the formulas spelled out according to their logic:
=IF(AND(A2>0,B2 0,B4 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 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.
Here are the formulas spelled out according to their logic:
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 B2,A4 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.
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.
Edit Rule dialog showing the Formula method» loading=»lazy»>
Using the earlier Dates example, here is what the formulas would be.
If A2 is greater than B2, format the cell, otherwise do nothing.
=AND(A3>B2,A3 B2,A4 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
Need more help?
See also
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
Источник
IF, AND, OR, Nested IF & NOT Logical Functions in Excel
Updated February 25, 2023
Things will not always be the way we want them to be. The unexpected can happen. For example, let’s say you have to divide numbers. Trying to divide any number by zero (0) gives an error. Logical functions come in handy such cases. In this tutorial, we are going to cover the following topics.
In this tutorial, we are going to cover the following topics.
What is a Logical Function?
It is a feature that allows us to introduce decision-making when executing formulas and functions. Functions are used to;
- Check if a condition is true or false
- Combine multiple conditions together
What is a condition and why does it matter?
A condition is an expression that either evaluates to true or false. The expression could be a function that determines if the value entered in a cell is of numeric or text data type, if a value is greater than, equal to or less than a specified value, etc.
IF Function example
We will work with the home supplies budget from this tutorial. We will use the IF function to determine if an item is expensive or not. We will assume that items with a value greater than 6,000 are expensive. Those that are less than 6,000 are less expensive. The following image shows us the dataset that we will work with.
- Put the cursor focus in cell F4
- Enter the following formula that uses the IF function
=IF(E4 0,ISNUMBER(1)) The above function returns TRUE because both Condition is True. 02 FALSE Logical Returns the logical value FALSE. It is used to compare the results of a condition or function that either returns true or false FALSE() 03 IF Logical Verifies whether a condition is met or not. If the condition is met, it returns true. If the condition is not met, it returns false.
=IF(logical_test,[value_if_true],[value_if_false]) =IF(ISNUMBER(22),”Yes”, “No”)
22 is Number so that it return Yes. 04 IFERROR Logical Returns the expression value if no error occurs. If an error occurs, it returns the error value =IFERROR(5/0,”Divide by zero error”) 05 IFNA Logical Returns value if #N/A error does not occur. If #N/A error occurs, it returns NA value. #N/A error means a value if not available to a formula or function. =IFNA(D6*E6,0)
N.B the above formula returns zero if both or either D6 or E6 is/are empty 06 NOT Logical Returns true if the condition is false and returns false if condition is true =NOT(ISTEXT(0))
N.B. the above function returns true. This is because ISTEXT(0) returns false and NOT function converts false to TRUE 07 OR Logical Used when evaluating multiple conditions. Returns true if any or all of the conditions are true. Returns false if all of the conditions are false =OR(D8=”admin”,E8=”cashier”)
N.B. the above function returns true if either or both D8 and E8 admin or cashier 08 TRUE Logical Returns the logical value TRUE. It is used to compare the results of a condition or function that either returns true or false TRUE()
Nested IF functions
A nested IF function is an IF function within another IF function. Nested if statements come in handy when we have to work with more than two conditions. Let’s say we want to develop a simple program that checks the day of the week. If the day is Saturday we want to display “party well”, if it’s Sunday we want to display “time to rest”, and if it’s any day from Monday to Friday we want to display, remember to complete your to do list.
A nested if function can help us to implement the above example. The following flowchart shows how the nested IF function will be implemented.
The formula for the above flowchart is as follows
=IF(B1=”Sunday”,”time to rest”,IF(B1=”Saturday”,”party well”,”to do list”))
HERE,
- “=IF(….)” is the main if function
- “=IF(…,IF(….))” the second IF function is the nested one. It provides further evaluation if the main IF function returned false.
Practical example
Create a new workbook and enter the data as shown below
- Enter the following formula
=IF(B1=”Sunday”,”time to rest”,IF(B1=”Saturday”,”party well”,”to do list”))
- Enter Saturday in cell address B1
- You will get the following results
Summary
Logical functions are used to introduce decision-making when evaluating formulas and functions in Excel.
Источник
Excel IF statement with multiple conditions
by Svetlana Cheusheva, updated on February 7, 2023
The tutorial shows how to create multiple IF statements in Excel with AND as well as OR logic. Also, you will learn how to use IF together with other Excel functions.
In the first part of our Excel IF tutorial, we looked at how to construct a simple IF statement with one condition for text, numbers, dates, blanks and non-blanks. For powerful data analysis, however, you may often need to evaluate multiple conditions at a time. The below formula examples will show you the most effective ways to do this.
How to use IF function with multiple conditions
In essence, there are two types of the IF formula with multiple criteria based on the AND / OR logic. Consequently, in the logical test of your IF formula, you should use one of these functions:
- AND function — returns TRUE if all the conditions are met; FALSE otherwise.
- OR function — returns TRUE if any single condition is met; FALSE otherwise.
To better illustrate the point, let’s investigate some real-life formulas examples.
Excel IF statement with multiple conditions (AND logic)
The generic formula of Excel IF with two or more conditions is this:
Translated into a human language, the formula says: If condition 1 is true AND condition 2 is true, return value_if_true; else return value_if_false.
Suppose you have a table listing the scores of two tests in columns B and C. To pass the final exam, a student must have both scores greater than 50.
For the logical test, you use the following AND statement: AND(B2>50, C2>50)
If both conditions are true, the formula will return «Pass»; if any condition is false — «Fail».
=IF(AND(B2>50, B2>50), «Pass», «Fail»)
Easy, isn’t it? The screenshot below proves that our Excel IF /AND formula works right:
In a similar manner, you can use the Excel IF function with multiple text conditions.
For instance, to output «Good» if both B2 and C2 are greater than 50, «Bad» otherwise, the formula is:
=IF(AND(B2=»pass», C2=»pass»), «Good!», «Bad»)
Important note! The AND function checks all the conditions, even if the already tested one(s) evaluated to FALSE. Such behavior is a bit unusual since in most of programming languages, subsequent conditions are not tested if any of the previous tests has returned FALSE.
In practice, a seemingly correct IF statement may result in an error because of this specificity. For example, the below formula would return #DIV/0! («divide by zero» error) if cell A2 is equal to 0:
The avoid this, you should use a nested IF function:
=IF(A2<>0, IF((1/A2)>0.5, «Good», «Bad»), «Bad»)
For more information, please see IF AND formula in Excel.
Excel IF function with multiple conditions (OR logic)
To do one thing if any condition is met, otherwise do something else, use this combination of the IF and OR functions:
The difference from the IF / AND formula discussed above is that Excel returns TRUE if any of the specified conditions is true.
So, if in the previous formula, we use OR instead of AND:
=IF(OR(B2>50, B2>50), «Pass», «Fail»)
Then anyone who has more than 50 points in either exam will get «Pass» in column D. With such conditions, our students have a better chance to pass the final exam (Yvette being particularly unlucky failing by just 1 point 🙂
Tip. In case you are creating a multiple IF statement with text and testing a value in one cell with the OR logic (i.e. a cell can be «this» or «that»), then you can build a more compact formula using an array constant.
For example, to mark a sale as «closed» if cell B2 is either «delivered» or «paid», the formula is:
More formula examples can be found in Excel IF OR function.
IF with multiple AND & OR statements
If your task requires evaluating several sets of multiple conditions, you will have to utilize both AND & OR functions at a time.
In our sample table, suppose you have the following criteria for checking the exam results:
- Condition 1: exam1>50 and exam2>50
- Condition 2: exam1>40 and exam2>60
If either of the conditions is met, the final exam is deemed passed.
At first sight, the formula seems a little tricky, but in fact it is not! You just express each of the above conditions as an AND statement and nest them in the OR function (since it’s not necessary to meet both conditions, either will suffice):
OR(AND(B2>50, C2>50), AND(B2>40, C2>60)
Then, use the OR function for the logical test of IF and supply the desired value_if_true and value_if_false values. As the result, you get the following IF formula with multiple AND / OR conditions:
=IF(OR(AND(B2>50, C2>50), AND(B2>40, C2>60), «Pass», «Fail»)
The screenshot below indicates that we’ve done the formula right:
Naturally, you are not limited to using only two AND/OR functions in your IF formulas. You can use as many of them as your business logic requires, provided that:
- In Excel 2007 and higher, you have no more than 255 arguments, and the total length of the IF formula does not exceed 8,192 characters.
- In Excel 2003 and lower, there are no more than 30 arguments, and the total length of your IF formula does not exceed 1,024 characters.
Nested IF statement to check multiple logical tests
If you want to evaluate multiple logical tests within a single formula, then you can nest several functions one into another. Such functions are called nested IF functions. They prove particularly useful when you wish to return different values depending on the logical tests’ results.
Here’s a typical example: suppose you want to qualify the students’ achievements as «Good«, «Satisfactory» and «Poor» based on the following scores:
- Good: 60 or more (>=60)
- Satisfactory: between 40 and 60 (>40 and =IF(B2>=60, «Good», IF(B2>40, «Satisfactory», «Poor»))
Naturally, you can nest more functions if needed (up to 64 in modern versions).
Excel IF array formula with multiple conditions
Another way to get an Excel IF to test multiple conditions is by using an array formula.
To evaluate conditions with the AND logic, use the asterisk:
To test conditions with the OR logic, use the plus sign:
To complete an array formula correctly, press the Ctrl + Shift + Enter keys together. In Excel 365 and Excel 2021, this also works as a regular formula due to support for dynamic arrays.
For example, to get «Pass» if both B2 and C2 are greater than 50, the formula is:
=IF((B2>50) * (C2>50), «Pass», «Fail»)
In my Excel 365, a normal formula works just fine (as you can see in the screenshots above). In Excel 2019 and lower, remember to make it an array formula by using the Ctrl + Shift + Enter shortcut.
To evaluate multiple conditions with the OR logic, the formula is:
=IF((B2>50) + (C2>50), «Pass», «Fail»)
Using IF together with other functions
This section explains how to use IF in combination with other Excel functions and what benefits this gives to you.
Example 1. If #N/A error in VLOOKUP
When VLOOKUP or other lookup function cannot find something, it returns a #N/A error. To make your tables look nicer, you can return zero, blank, or specific text if #N/A. For this, use this generic formula:
If the lookup value in E1 is not found, the formula returns zero.
=IF(ISNA(VLOOKUP(E1, A2:B10, 2,FALSE )), 0, VLOOKUP(E1, A2:B10, 2, FALSE))
If #N/A return blank:
If the lookup value is not found, the formula returns nothing (an empty string).
=IF(ISNA(VLOOKUP(E1, A2:B10, 2,FALSE )), «», VLOOKUP(E1, A2:B10, 2, FALSE))
If #N/A return certain text:
If the lookup value is not found, the formula returns specific text.
=IF(ISNA(VLOOKUP(E1, A2:B10, 2,FALSE )), «Not found», VLOOKUP(E1, A2:B10, 2, FALSE))
For more formula examples, please see VLOOKUP with IF statement in Excel.
Example 2. IF with SUM, AVERAGE, MIN and MAX functions
To sum cell values based on certain criteria, Excel provides the SUMIF and SUMIFS functions.
In some situations, your business logic may require including the SUM function in the logical test of IF. For example, to return different text labels depending on the sum of the values in B2 and C2, the formula is:
=IF(SUM(B2:C2)>130, «Good», IF(SUM(B2:C2)>110, «Satisfactory», «Poor»))
If the sum is greater than 130, the result is «good»; if greater than 110 – «satisfactory’, if 110 or lower – «poor».
In a similar fashion, you can embed the AVERAGE function in the logical test of IF and return different labels based on the average score:
=IF(AVERAGE(B2:C2)>65, «Good», IF(AVERAGE(B2:C2)>55, «Satisfactory», «Poor»))
Assuming the total score is in column D, you can identify the highest and lowest values with the help of the MAX and MIN functions:
=IF(D2=MAX($D$2:$D$10), «Best result», «»)
=IF(D2=MAX($D$2:$D$10), «Best result», «»)
To have both labels in one column, nest the above functions one into another:
=IF(D2=MAX($D$2:$D$10), «Best result», IF(D2=MIN($D$2:$D$10), «Worst result», «»))
Likewise, you can use IF together with your custom functions. For example, you can combine it with GetCellColor or GetCellFontColor to return different results based on a cell color.
In addition, Excel provides a number of functions to calculate data based on conditions. For detailed formula examples, please check out the following tutorials:
- COUNTIF — count cells that meet a condition
- COUNTIFS — count cells with multiple criteria
- SUMIF — conditionally sum cells
- SUMIFS — sum cells with multiple criteria
Example 3. IF with ISNUMBER, ISTEXT and ISBLANK
To identify text, numbers and blank cells, Microsoft Excel provides special functions such as ISTEXT, ISNUMBER and ISBLANK. By placing them in the logical tests of three nested IF statements, you can identify all different data types in one go:
=IF(ISTEXT(A2), «Text», IF(ISNUMBER(A2), «Number», IF(ISBLANK(A2), «Blank», «»)))
Example 4. IF and CONCATENATE
To output the result of IF and some text into one cell, use the CONCATENATE or CONCAT (in Excel 2016 — 365) and IF functions together. For example:
=CONCATENATE(«You performed «, IF(B1>100,»fantastic!», IF(B1>50, «well», «poor»)))
=CONCAT(«You performed «, IF(B1>100,»fantastic!», IF(B1>50, «well», «poor»)))
Looking at the screenshot below, you’ll hardly need any explanation of what the formula does:
IF ISERROR / ISNA formula in Excel
The modern versions of Excel have special functions to trap errors and replace them with another calculation or predefined value — IFERROR (in Excel 2007 and later) and IFNA (in Excel 2013 and later). In earlier Excel versions, you can use the IF ISERROR and IF ISNA combinations instead.
The difference is that IFERROR and ISERROR handle all possible Excel errors, including #VALUE!, #N/A, #NAME?, #REF!, #NUM!, #DIV/0!, and #NULL!. While IFNA and ISNA specialize solely in #N/A errors.
For example, to replace the «divide by zero» error (#DIV/0!) with your custom text, you can use the following formula:
=IF(ISERROR(A2/B2), «N/A», A2/B2)
And that’s all I have to say about using the IF function in Excel. I thank you for reading and hope to see you on our blog next week!
Источник
To write an IF, AND, OR array formula in Excel 365, we must use the arithmetic operators * (multiplication) and + (addition). Why it’s so?
If we take the logical AND, OR with the IF in Excel 365 to spill the result, we won’t get our expected result.
I mean, such a formula won’t support a range/array in evaluation. Even if it supports, it won’t return an array result.
So we will replace the AND logical operator with the * (multiplication) and OR with the + (addition) arithmetic operators.
Coding the formula with the said two operators is very simple and easily readable.
I think I can convince you the same with the examples below.
Example to IF, AND, OR in Excel 365 (Non-Array Formula)
Imagine a user played a game three times, and we have recorded his scores out of 100 in cells A2, B2, and C2.
We want to perform the following three logical tests on the scores individually.
- If all scores are >=80, return OK.
- If any of the two scores are >=80, return OK.
- Finally, if any of the scores is >=80, return OK.
Logical Tests Using IF, AND, OR Functions
In Excel, we can perform the above three logical tests as follows.
1. E2 (If all scores are >=80, return OK)
=IF(AND(A2>=80,B2>=80,C2>=80),"OK","NOT OK")
I have used the AND function with IF in the above Excel formula to test if all the three logical tests return TRUE.
2. F2 (If any of the two scores are >=80, return OK)
We must use the following logic (two parts) to test if any two logical tests return TRUE.
AND Part:-
a) Value 1>=80 and value 2>=80.
b) Value 1>=80 and value 3>=80.
c) Value 2>=80 and value 3>=80.
OR Part:-
a) The OR evaluates to TRUE if any two of the above three AND tests return TRUE.
So the formula will be as follows.
=IF(OR(AND(A2>=80,B2>=80),AND(A2>=80,C2>=80),AND(B2>=80,C2>=80)),"OK","NOT OK")
It is an example of the IF, AND, OR logical test in Excel.
3. G2 (if any of the scores is >=80, return OK)
=IF(OR(A2>=80,B2>=80,C2>=80),"OK","NOT OK")
Here I have used the OR function with IF to test if any of the three logical tests return TRUE.
As I have already mentioned, we can’t write an IF, AND, OR array formula as above in Excel 365.
Logical Tests Using IF, *, + Formula
Let’s substitute the above three formulas by replacing AND, OR with multiplication and addition.
But that’s not enough. Then?
The below formulas are self-explanatory.
1. E2 Formula
=IF((A2:A8>=80)*(B2:B8>=80)*(C2:C8>=80),"OK","NOT OK")
How the multiplication replaces the logical function OR above?
Each test in the formula returns either TRUE or FALSE. If all the criteria are met, it will be =IF((TRUE*TRUE*TRUE),"OK","NOT OK")
.
We can even replace the multiplication operator here with addition.
=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>2,"OK","NOT OK")
Please remember that the value of TRUE is 1, and FALSE is 0.
2. F2 Formula
=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>1,"OK","NOT OK")
3. G2 Formula
=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>0,"OK","NOT OK")
Above I have tried to simplify the use of the logical operators within the IF function.
Now let’s open an Excel Spreadsheet and enter the scores of multiple players in the range A2:C8 as below.
So the values to evaluate are in cell range A2:C8.
I have inserted the following three IF, AND, OR array formulas in cells E2, F2, and G2, respectively.
1. E2 Array Formula
=IF((A2:A8>=80)*(B2:B8>=80)*(C2:C8>=80),"OK","NOT OK")
2. F2 Array Formula
=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>1,"OK","NOT OK")
3. G2 Array Formula
=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>0,"OK","NOT OK")
If any of the above formulas return #SPILL!, please empty the cells down in that column.
Nested IF, AND, OR Combination in Excel 365
I want to assign grades based on the scores above.
In that case, we may require to write a nested IF, AND, OR combination array formula in Excel 365.
Here is how.
In the above example, we have used three formulas for the below three logical tests.
- If all scores are >=80, return OK.
- If any of the two scores are >=80, return OK.
- Finally, if any of the scores is >=80, return OK.
There each test returns OK or NOT OK.
Instead of that, here, I want the tests to return GR-1, GR-2, and GR-3.
- If all scores are >=80, return GR-1.
- If any of the two scores are >=80, return GR-2.
- Finally, if any of the scores is >=80, return GR-3.
For that, we should combine the above three IF, AND, OR Array Formulas.
How?
In the E2 formula, replace “OK” with “GR-1” and “NOT OK” with the F2 formula.
In that combined (E2 and F2) formula, replace “OK” with “GR-2” and “NOT OK” with the G2 formula.
Then, in the combined E2, F2, and G2 formula, replace “OK” with “GR-3” and replace “NOT OK” with “F.”
Here it is.
=IF(
(A2:A8>=80)*(B2:B8>=80)*(C2:C8>=80),"GR-1",
IF(
(A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>1,"GR-2",
IF(
(A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>0,"GR-3","F"
)
)
)
We can call it a nested IF, AND, OR combination array formula.
Related:- How to Use the IFS Function in Excel 365.
Excel IF AND OR functions on their own aren’t very exciting, but mix them up with the IF Statement and you’ve got yourself a formula that’s much more powerful.
In this tutorial we’re going to take a look at the basics of the AND and OR functions and then put them to work with an IF Statement. If you aren’t familiar with IF Statements, click here to read that tutorial first.
IF Formula Builder
Our IF Formula Builder does the hard work of creating IF formulas.
You just need to enter a few pieces of information, and the workbook creates the formula for you.
AND Function
The AND function belongs to the logic family of formulas, along with IF, OR and a few others. It’s useful when you have multiple conditions that must be met.
In Excel language on its own the AND formula reads like this:
=AND(logical1,[logical2]....)
Now to translate into English:
=AND(is condition 1 true, AND condition 2 true (add more conditions if you want)
OR Function
The OR function is useful when you are happy if one, OR another condition is met.
In Excel language on its own the OR formula reads like this:
=OR(logical1,[logical2]....)
Now to translate into English:
=OR(is condition 1 true, OR condition 2 true (add more conditions if you want)
See, I did say they weren’t very exciting, but let’s mix them up with IF and put AND and OR to work.
IF AND Formula
First let’s set the scene of our challenge for the IF, AND formula:
In our spreadsheet below we want to calculate a bonus to pay the children’s TV personalities listed. The rules, as devised by my 4 year old son, are:
1) If the TV personality is Popular AND
2) If they earn less than $100k per year they get a 10% bonus (my 4 year old will write them an IOU, he’s good for it though).
In cell D2 we will enter our IF AND formula as follows:
In English first
=IF(Spider Man is Popular, AND he earns <$100k), calculate his salary x 10%, if not put "Nil" in the cell)
Now in Excel’s language:
=IF(AND(B2="Yes",C2<100),C2x$H$1,"Nil")
You’ll notice that the two conditions are typed in first, and then the outcomes are entered. You can have more than two conditions; in fact you can have up to 30 by simply separating each condition with a comma (see warning below about going overboard with this though).
IF OR Formula
Again let’s set the scene of our challenge for the IF, OR formula:
The revised rules, as devised by my 4 year old son, are:
1) If the TV personality is Popular OR
2) If they earn less than $100k per year they get a 10% bonus.
In cell D2 we will enter our IF OR formula as follows:
In English first
=IF(Spider Man is Popular, OR he earns <$100k), calculate his salary x 10%, if not put “Nil” in the cell)
Now in Excel’s language:
=IF(OR(B2="Yes",C2<100),C2x$H$1,"Nil")
Notice how a subtle change from the AND function to the OR function has a significant impact on the bonus figure.
Just like the AND function, you can have up to 30 OR conditions nested in the one formula, again just separate each condition with a comma.
Try other operators
You can set your conditions to test for specific text, as I have done in this example with B2=»Yes», just put the text you want to check between inverted comas “ ”.
Alternatively you can test for a number and because the AND and OR functions belong to the logic family, you can employ different tests other than the less than (<) operator used in the examples above.
Other operators you could use are:
- = Equal to
- > Greater Than
- <= Less than or equal to
- >= Greater than or equal to
- <> Less than or greater than
Warning: Don’t go overboard with nesting IF, AND, and OR’s, as it will be painful to decipher if you or someone else ever needs to update the formula in months or years to come.
Note: These formulas work in all versions of Excel, however versions pre Excel 2007 are limited to 7 nested IF’s.
Download the Workbook
Enter your email address below to download the sample workbook.
By submitting your email address you agree that we can email you our Excel newsletter.
Excel IF AND OR Practice Questions
IF AND Formula Practice
In the embedded Excel workbook below insert a formula (in the grey cells in column E), that returns the text ‘Yes’, when a product SKU should be reordered, based on the following criteria:
- If Stock on hand is less than 20,000 AND
- Demand level is ‘High’
If the above conditions are met, return ‘Yes’, otherwise, return ‘No’.
Tips for working with the embedded workbook:
- Use arrow keys to move around the worksheet when you can’t click on the cells with your mouse
- Use shortcut keys CTRL+C to copy and CTRL+V to paste
- Don’t forget to absolute cell references where applicable
- Do not enter anything in column F
- Double click to edit a cell
- Refresh the page to reset the embedded workbook
IF OR Formula Practice
In the embedded Excel workbook below insert a formula (in the grey cells in column E) that calculates the bonus due for each salesperson. A $500 bonus is paid if a salesperson meets either target in cells C24 and C25, otherwise they earn $0 bonus.
Want More Excel Formulas
Why not visit our list of Excel formulas. You’ll find a huge range all explained in plain English, plus PivotTables and other Excel tools and tricks. Enjoy 🙂
Как использовать функцию IF
Функция IF — это основная логическая функция в Excel, и поэтому она должна быть понятна первой. Он появится много раз на протяжении всей этой статьи.
Давайте посмотрим на структуру функции IF, а затем посмотрим несколько примеров ее использования.
Функция IF принимает 3 бита информации:
= IF (логический_тест, [value_if_true], [value_if_false])
- логический_тест: это условие для функции для проверки.
- value_if_true: действие, которое выполняется, если условие выполнено или является истинным.
- value_if_false: действие, которое нужно выполнить, если условие не выполнено или имеет значение false.
Операторы сравнения для использования с логическими функциями
При выполнении логического теста со значениями ячеек вы должны быть знакомы с операторами сравнения. Вы можете увидеть их в таблице ниже.
Теперь давайте посмотрим на некоторые примеры в действии.
Пример функции IF 1: текстовые значения
В этом примере мы хотим проверить, равна ли ячейка определенной фразе. Функция IF не учитывает регистр, поэтому не учитывает прописные и строчные буквы.
Следующая формула используется в столбце C для отображения «Нет», если столбец B содержит текст «Завершено» и «Да», если он содержит что-либо еще.
= ЕСЛИ (B2 = "Завершено", "Нет", "Да")
Хотя функция IF не чувствительна к регистру, текст должен точно соответствовать.
Пример функции IF 2: Числовые значения
Функция IF также отлично подходит для сравнения числовых значений.
В приведенной ниже формуле мы проверяем, содержит ли ячейка B2 число, большее или равное 75. Если это так, то мы отображаем слово «Pass», а если не слово «Fail».
= ЕСЛИ (В2> = 75, "Проход", "Сбой")
Функция IF — это намного больше, чем просто отображение разного текста в результате теста. Мы также можем использовать его для запуска различных расчетов.
В этом примере мы хотим предоставить скидку 10%, если клиент тратит определенную сумму денег. Мы будем использовать £ 3000 в качестве примера.
= ЕСЛИ (В2> = 3000, В2 * 90%, В2)
Часть формулы B2 * 90% позволяет вычесть 10% из значения в ячейке B2. Есть много способов сделать это.
Важно то, что вы можете использовать любую формулу в разделах value_if_true
или value_if_false
. И запускать различные формулы, зависящие от значений других ячеек, — очень мощный навык.
Пример функции IF 3: значения даты
В этом третьем примере мы используем функцию IF для отслеживания списка сроков исполнения. Мы хотим отобразить слово «Просрочено», если дата в столбце B уже в прошлом. Но если дата наступит в будущем, рассчитайте количество дней до даты исполнения.
Приведенная ниже формула используется в столбце C. Мы проверяем, меньше ли срок оплаты в ячейке B2, чем сегодняшний день (функция TODAY возвращает сегодняшнюю дату с часов компьютера).
= ЕСЛИ (В2 <СЕГОДНЯ (), "Просроченные", В2-СЕГОДНЯ ())
Что такое вложенные формулы IF?
Возможно, вы слышали о термине «вложенные IF» раньше. Это означает, что мы можем написать функцию IF внутри другой функции IF. Мы можем захотеть сделать это, если нам нужно выполнить более двух действий.
Одна функция IF способна выполнять два действия ( value_if_true
и value_if_false
). Но если мы вставим (или вложим) другую функцию IF в раздел value_if_false
, то мы можем выполнить другое действие.
Возьмите этот пример, где мы хотим отобразить слово «Отлично», если значение в ячейке B2 больше или равно 90, отобразить «Хорошо», если значение больше или равно 75, и отобразить «Плохо», если что-либо еще ,
= ЕСЛИ (В2> = 90, "Отлично", ЕСЛИ (В2> = 75, "Хорошо", "Плохо"))
Теперь мы расширили нашу формулу за пределы того, что может сделать только одна функция IF. И вы можете вложить больше функций IF, если это необходимо.
Обратите внимание на две закрывающие скобки в конце формулы — по одной для каждой функции IF.
Существуют альтернативные формулы, которые могут быть чище, чем этот вложенный подход IF. Одной из очень полезных альтернатив является функция SWITCH в Excel .
Логические функции AND и OR
Функции AND и OR используются, когда вы хотите выполнить более одного сравнения в своей формуле. Одна только функция IF может обрабатывать только одно условие или сравнение.
Возьмите пример, где мы дисконтируем значение на 10% в зависимости от суммы, которую тратит клиент, и сколько лет они были клиентом.
Сами функции AND и OR возвращают значение TRUE или FALSE.
Функция AND возвращает TRUE, только если выполняется каждое условие, а в противном случае возвращает FALSE. Функция OR возвращает TRUE, если выполняется одно или все условия, и возвращает FALSE, только если условия не выполняются.
Эти функции могут тестировать до 255 условий, поэтому они не ограничены только двумя условиями, как показано здесь.
Ниже приведена структура функций И и ИЛИ. Они написаны одинаково. Просто замените имя И на ИЛИ. Это просто их логика, которая отличается.
= И (логический1, [логический2] ...)
Давайте посмотрим на пример того, как они оба оценивают два условия.
Пример функции AND
Функция AND используется ниже, чтобы проверить, потратил ли клиент не менее 3000 фунтов стерлингов и был ли он клиентом не менее трех лет.
= И (В2> = 3000, С2> = 3)
Вы можете видеть, что он возвращает FALSE для Мэтта и Терри, потому что, хотя они оба соответствуют одному из критериев, они должны соответствовать обеим функциям AND.
Пример функции OR
Функция ИЛИ используется ниже, чтобы проверить, потратил ли клиент не менее 3000 фунтов стерлингов или был клиентом не менее трех лет.
= ИЛИ (В2> = 3000, С2> = 3)
В этом примере формула возвращает TRUE для Matt и Terry. Только Джули и Джиллиан не выполняют оба условия и возвращают значение FALSE.
Использование AND и OR с функцией IF
Поскольку функции И и ИЛИ возвращают значение ИСТИНА или ЛОЖЬ, когда используются по отдельности, они редко используются сами по себе.
Вместо этого вы обычно будете использовать их с функцией IF или внутри функции Excel, такой как условное форматирование или проверка данных, чтобы выполнить какое-либо ретроспективное действие, если формула имеет значение TRUE.
В приведенной ниже формуле функция AND вложена в логический тест функции IF. Если функция AND возвращает TRUE, тогда скидка 10% от суммы в столбце B; в противном случае скидка не предоставляется, а значение в столбце B повторяется в столбце D.
= ЕСЛИ (И (В2> = 3000, С2> = 3), В2 * 90%, В2)
Функция XOR
В дополнение к функции ИЛИ, есть также эксклюзивная функция ИЛИ. Это называется функцией XOR. Функция XOR была представлена в версии Excel 2013.
Эта функция может потребовать некоторых усилий, чтобы понять, поэтому практический пример показан.
Структура функции XOR такая же, как у функции OR.
= XOR (логический1, [логический2] ...)
При оценке только двух условий функция XOR возвращает:
- ИСТИНА, если любое условие оценивается как ИСТИНА.
- FALSE, если оба условия TRUE или ни одно из условий TRUE.
Это отличается от функции ИЛИ, потому что она вернула бы ИСТИНА, если оба условия были ИСТИНА.
Эта функция становится немного более запутанной, когда добавляется больше условий. Затем функция XOR возвращает:
- TRUE, если нечетное число условий возвращает TRUE.
- ЛОЖЬ, если четное число условий приводит к ИСТИНА, или если все условия ЛОЖЬ.
Давайте посмотрим на простой пример функции XOR.
В этом примере продажи делятся на две половины года. Если продавец продает 3000 и более фунтов стерлингов в обеих половинах, ему назначается Золотой стандарт. Это достигается с помощью функции AND с IF, как ранее в этой статье.
Но если они продают 3000 фунтов или более в любой половине, мы хотим присвоить им Серебряный статус. Если они не продают 3000 и более фунтов стерлингов в обоих случаях, то ничего.
Функция XOR идеально подходит для этой логики. Приведенная ниже формула вводится в столбец E и показывает функцию XOR с IF для отображения «Да» или «Нет», только если выполняется любое из условий.
= IF (XOR (В2> = 3000, С2> = 3000), "Да", "Нет")
Функция НЕ
Последняя логическая функция для обсуждения в этой статье — это функция NOT, и мы оставим самую простую последнюю. Хотя иногда поначалу бывает трудно увидеть использование этой функции в реальном мире.
Функция NOT меняет значение своего аргумента. Так что, если логическое значение ИСТИНА, тогда оно возвращает ЛОЖЬ. И если логическое значение ЛОЖЬ, оно вернет ИСТИНА.
Это будет легче объяснить на некоторых примерах.
Структура функции НЕ имеет вид;
= НЕ (логическое)
НЕ Функциональный Пример 1
В этом примере представьте, что у нас есть головной офис в Лондоне, а затем много других региональных сайтов. Мы хотим отобразить слово «Да», если на сайте есть что-то, кроме Лондона, и «Нет», если это Лондон.
Функция NOT была вложена в логический тест функции IF ниже, чтобы сторнировать ИСТИННЫЙ результат.
= ЕСЛИ (НЕ (B2 = "London"), "Да", "Нет")
Это также может быть достигнуто с помощью логического оператора NOT <>. Ниже приведен пример.
= ЕСЛИ (В2 <> "Лондон", "Да", "Нет")
НЕ Функциональный Пример 2
Функция NOT полезна при работе с информационными функциями в Excel. Это группа функций в Excel, которые что-то проверяют и возвращают TRUE, если проверка прошла успешно, и FALSE, если это не так.
Например, функция ISTEXT проверит, содержит ли ячейка текст, и вернет TRUE, если она есть, и FALSE, если нет. Функция NOT полезна, потому что она может отменить результат этих функций.
В приведенном ниже примере мы хотим заплатить продавцу 5% от суммы, которую он продает. Но если они ничего не перепродали, в ячейке есть слово «Нет», и это приведет к ошибке в формуле.
Функция ISTEXT используется для проверки наличия текста. Это возвращает TRUE, если текст есть, поэтому функция NOT переворачивает это на FALSE. И если ИФ выполняет свой расчет.
= ЕСЛИ (НЕ (ISTEXT (В2)), В2 * 5%, 0)
Овладение логическими функциями даст вам большое преимущество как пользователю Excel. Очень полезно иметь возможность проверять и сравнивать значения в ячейках и выполнять различные действия на основе этих результатов.
В этой статье рассматриваются лучшие логические функции, используемые сегодня. В последних версиях Excel появилось больше функций, добавленных в эту библиотеку, таких как функция XOR, упомянутая в этой статье. Будьте в курсе этих новых дополнений, вы будете впереди толпы.