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)
Содержание
- IF function – nested formulas and avoiding pitfalls
- Remarks
- Examples
- Additional examples
- Did you know?
- Need more help?
- Using IF with AND, OR and NOT functions
- Examples
- Using AND, OR and NOT with Conditional Formatting
- Need more help?
- See also
- Использование ЕСЛИ с функциями И, ИЛИ и НЕ
- Примеры
- Использование операторов И, ИЛИ и НЕ с условным форматированием
- Дополнительные сведения
- См. также
IF function – nested formulas and avoiding pitfalls
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 True or False.
=IF(Something is True, then do something, otherwise do something else)
So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.
IF statements are incredibly robust, and form the basis of many spreadsheet models, but they are also the root cause of many spreadsheet issues. Ideally, an IF statement should apply to minimal conditions, such as Male/Female, Yes/No/Maybe, to name a few, but sometimes you might need to evaluate more complex scenarios that require nesting* more than 3 IF functions together.
* “Nesting” refers to the practice of joining multiple functions together in one formula.
Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it’s false.
IF(logical_test, 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.
While Excel will allow you to nest up to 64 different IF functions, it’s not at all advisable to do so. Why?
Multiple IF statements require a great deal of thought to build correctly and make sure that their logic can calculate correctly through each condition all the way to the end. If you don’t nest your formula 100% accurately, then it might work 75% of the time, but return unexpected results 25% of the time. Unfortunately, the odds of you catching the 25% are slim.
Multiple IF statements can become incredibly difficult to maintain, especially when you come back some time later and try to figure out what you, or worse someone else, was trying to do.
If you find yourself with an IF statement that just seems to keep growing with no end in sight, it’s time to put down the mouse and rethink your strategy.
Let’s look at how to properly create a complex nested IF statement using multiple IFs, and when to recognize that it’s time to use another tool in your Excel arsenal.
Examples
Following is an example of a relatively standard nested IF statement to convert student test scores to their letter grade equivalent.
97,»A+»,IF(B2>93,»A»,IF(B2>89,»A-«,IF(B2>87,»B+»,IF(B2>83,»B»,IF(B2>79,»B-«,IF(B2>77,»C+»,IF(B2>73,»C»,IF(B2>69,»C-«,IF(B2>57,»D+»,IF(B2>53,»D»,IF(B2>49,»D-«,»F»))))))))))))» loading=»lazy»>
This complex nested IF statement follows a straightforward logic:
If the Test Score (in cell D2) is greater than 89, then the student gets an A
If the Test Score is greater than 79, then the student gets a B
If the Test Score is greater than 69, then the student gets a C
If the Test Score is greater than 59, then the student gets a D
Otherwise the student gets an F
This particular example is relatively safe because it’s not likely that the correlation between test scores and letter grades will change, so it won’t require much maintenance. But here’s a thought – what if you need to segment the grades between A+, A and A- (and so on)? Now your four condition IF statement needs to be rewritten to have 12 conditions! Here’s what your formula would look like now:
It’s still functionally accurate and will work as expected, but it takes a long time to write and longer to test to make sure it does what you want. Another glaring issue is that you’ve had to enter the scores and equivalent letter grades by hand. What are the odds that you’ll accidentally have a typo? Now imagine trying to do this 64 times with more complex conditions! Sure, it’s possible, but do you really want to subject yourself to this kind of effort and probable errors that will be really hard to spot?
Tip: Every function in Excel requires an opening and closing parenthesis (). Excel will try to help you figure out what goes where by coloring different parts of your formula when you’re editing it. For instance, if you were to edit the above formula, as you move the cursor past each of the ending parentheses “)”, its corresponding opening parenthesis will turn the same color. This can be especially useful in complex nested formulas when you’re trying to figure out if you have enough matching parentheses.
Additional examples
Following is a very common example of calculating Sales Commission based on levels of Revenue achievement.
15000,20%,IF(C9>12500,17.5%,IF(C9>10000,15%,IF(C9>7500,12.5%,IF(C9>5000,10%,0)))))» loading=»lazy»>
This formula says IF(C9 is Greater Than 15,000 then return 20%, IF(C9 is Greater Than 12,500 then return 17.5%, and so on.
While it’s remarkably similar to the earlier Grades example, this formula is a great example of how difficult it can be to maintain large IF statements – what would you need to do if your organization decided to add new compensation levels and possibly even change the existing dollar or percentage values? You’d have a lot of work on your hands!
Tip: You can insert line breaks in the formula bar to make long formulas easier to read. Just press ALT+ENTER before the text you want to wrap to a new line.
Here is an example of the commission scenario with the logic out of order:
5000,10%,IF(C9>7500,12.5%,IF(C9>10000,15%,IF(C9>12500,17.5%,IF(C9>15000,20%,0)))))» loading=»lazy»>
Can you see what’s wrong? Compare the order of the Revenue comparisons to the previous example. Which way is this one going? That’s right, it’s going from bottom up ($5,000 to $15,000), not the other way around. But why should that be such a big deal? It’s a big deal because the formula can’t pass the first evaluation for any value over $5,000. Let’s say you’ve got $12,500 in revenue – the IF statement will return 10% because it is greater than $5,000, and it will stop there. This can be incredibly problematic because in a lot of situations these types of errors go unnoticed until they’ve had a negative impact. So knowing that there are some serious pitfalls with complex nested IF statements, what can you do? In most cases, you can use the VLOOKUP function instead of building a complex formula with the IF function. Using VLOOKUP, you first need to create a reference table:
This formula says to look for the value in C2 in the range C5:C17. If the value is found, then return the corresponding value from the same row in column D.
Similarly, this formula looks for the value in cell B9 in the range B2:B22. If the value is found, then return the corresponding value from the same row in column C.
Note: Both of these VLOOKUPs use the TRUE argument at the end of the formulas, meaning we want them to look for an approxiate match. In other words, it will match the exact values in the lookup table, as well as any values that fall between them. In this case the lookup tables need to be sorted in Ascending order, from smallest to largest.
VLOOKUP is covered in much more detail here, but this is sure a lot simpler than a 12-level, complex nested IF statement! There are other less obvious benefits as well:
VLOOKUP reference tables are right out in the open and easy to see.
Table values can be easily updated and you never have to touch the formula if your conditions change.
If you don’t want people to see or interfere with your reference table, just put it on another worksheet.
Did you know?
There is now an IFS function that can replace multiple, nested IF statements with a single function. So instead of our initial grades example, which has 4 nested IF functions:
It can be made much simpler with a single IFS function:
The IFS function is great because you don’t need to worry about all of those IF statements and parentheses.
Note: This feature is only available if you have a Microsoft 365 subscription. If you are a Microsoft 365subscriber, make sure you have the latest version of Office.
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
Источник
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.
Источник
Использование ЕСЛИ с функциями И, ИЛИ и НЕ
Функция ЕСЛИ позволяет выполнять логические сравнения значений и ожидаемых результатов. Она проверяет условие и в зависимости от его истинности возвращает результат.
=ЕСЛИ(это истинно, то сделать это, в противном случае сделать что-то еще)
Но что делать, если необходимо проверить несколько условий, где, допустим, все условия должны иметь значение ИСТИНА или ЛОЖЬ ( И), только одно условие должно иметь такое значение ( ИЛИ) или вы хотите убедиться, что данные НЕ соответствуют условию? Эти три функции можно использовать самостоятельно, но они намного чаще встречаются в сочетании с функцией ЕСЛИ.
Используйте функцию ЕСЛИ вместе с функциями И, ИЛИ и НЕ, чтобы оценивать несколько условий.
ЕСЛИ(И()): ЕСЛИ(И(лог_выражение1; [лог_выражение2]; …), значение_если_истина; [значение_если_ложь]))
ЕСЛИ(ИЛИ()): ЕСЛИ(ИЛИ(лог_выражение1; [лог_выражение2]; …), значение_если_истина; [значение_если_ложь]))
ЕСЛИ(НЕ()): ЕСЛИ(НЕ(лог_выражение1), значение_если_истина; [значение_если_ложь]))
Условие, которое нужно проверить.
Значение, которое должно возвращаться, если лог_выражение имеет значение ИСТИНА.
Значение, которое должно возвращаться, если лог_выражение имеет значение ЛОЖЬ.
Общие сведения об использовании этих функций по отдельности см. в следующих статьях: И, ИЛИ, НЕ. При сочетании с оператором ЕСЛИ они расшифровываются следующим образом:
И: =ЕСЛИ(И(условие; другое условие); значение, если ИСТИНА; значение, если ЛОЖЬ)
ИЛИ: =ЕСЛИ(ИЛИ(условие; другое условие); значение, если ИСТИНА; значение, если ЛОЖЬ)
НЕ: =ЕСЛИ(НЕ(условие); значение, если ИСТИНА; значение, если ЛОЖЬ)
Примеры
Ниже приведены примеры распространенных случаев использования вложенных операторов ЕСЛИ(И()), ЕСЛИ(ИЛИ()) и ЕСЛИ(НЕ()). Функции И и ИЛИ поддерживают до 255 отдельных условий, но рекомендуется использовать только несколько условий, так как формулы с большой степенью вложенности сложно создавать, тестировать и изменять. У функции НЕ может быть только одно условие.
Ниже приведены формулы с расшифровкой их логики.
=ЕСЛИ(И(A2>0;B2 0;B4 50);ИСТИНА;ЛОЖЬ)
Если A6 (25) НЕ больше 50, возвращается значение ИСТИНА, в противном случае возвращается значение ЛОЖЬ. В этом случае значение не больше чем 50, поэтому формула возвращает значение ИСТИНА.
Если значение A7 («синий») НЕ равно «красный», возвращается значение ИСТИНА, в противном случае возвращается значение ЛОЖЬ.
Обратите внимание, что во всех примерах есть закрывающая скобка после условий. Аргументы ИСТИНА и ЛОЖЬ относятся ко внешнему оператору ЕСЛИ. Кроме того, вы можете использовать текстовые или числовые значения вместо значений ИСТИНА и ЛОЖЬ, которые возвращаются в примерах.
Вот несколько примеров использования операторов И, ИЛИ и НЕ для оценки дат.
Ниже приведены формулы с расшифровкой их логики.
Если A2 больше B2, возвращается значение ИСТИНА, в противном случае возвращается значение ЛОЖЬ. В этом случае 12.03.14 больше чем 01.01.14, поэтому формула возвращает значение ИСТИНА.
=ЕСЛИ(И(A3>B2;A3 B2;A4 B2);ИСТИНА;ЛОЖЬ)
Если A5 не больше B2, возвращается значение ИСТИНА, в противном случае возвращается значение ЛОЖЬ. В этом случае A5 больше B2, поэтому формула возвращает значение ЛОЖЬ.
Использование операторов И, ИЛИ и НЕ с условным форматированием
Вы также можете использовать операторы И, ИЛИ и НЕ в формулах условного форматирования. При этом вы можете опустить функцию ЕСЛИ.
На вкладке Главная выберите Условное форматирование > Создать правило. Затем выберите параметр Использовать формулу для определения форматируемых ячеек, введите формулу и примените формат.
«Изменить правило» с параметром «Формула»» loading=»lazy»>
Вот как будут выглядеть формулы для примеров с датами:
Если A2 больше B2, отформатировать ячейку, в противном случае не выполнять никаких действий.
=И(A3>B2;A3 B2;A4 B2)
Если A5 НЕ больше B2, отформатировать ячейку, в противном случае не выполнять никаких действий. В этом случае A5 больше B2, поэтому формула возвращает значение ЛОЖЬ. Если изменить формулу на =НЕ(B2>A5), она вернет значение ИСТИНА, а ячейка будет отформатирована.
Примечание: Распространенной ошибкой является ввод формулы в условное форматирование без знака равенства (=). В этом случае вы увидите, что диалоговое окно Условное форматирование добавит знак равенства и кавычки в формулу — =»OR(A4>B2,A4
Дополнительные сведения
См. также
Вы всегда можете задать вопрос специалисту Excel Tech Community или попросить помощи в сообществе Answers community.
Источник
We use the IF statement in Excel to test one condition and return one value if the condition is met and another if the condition is not met.
However, we use multiple or nested IF statements when evaluating numerous conditions in a specific order to return different results.
This tutorial shows four examples of using nested IF statements in Excel and gives five alternatives to using multiple IF statements in Excel.
General Syntax of Nested IF Statements (Multiple IF Statements)
The general syntax for nested IF statements is as follows:
=IF(Condition1, Value_if_true1, IF(Condition2, Value_if_true2, IF(Condition3, Value_if_true3, Value_if_false)))
This formula tests the first condition; if true, it returns the first value.
If the first condition is false, the formula moves to the second condition and returns the second value if it’s true.
Each subsequent IF function is incorporated into the value_if_false argument of the previous IF function.
This process continues until all conditions have been evaluated, and the formula returns the final value if none of the conditions is true.
The maximum number of nested IF statements allowed in Excel is 64.
Now, look at the following four examples of how to use nested IF statements in Excel.
Example #1: Use Multiple IF Statements to Assign Letter Grades Based on Numeric Scores
Let’s consider the following dataset showing some students’ scores on a Math test.
We want to use nested IF statements to assign student letter grades based on their scores.
We use the following steps:
- Select cell C2 and type in the below formula:
=IF(B2>=90,"A",IF(B2>=80,"B",IF(B2>=70,"C",IF(B2>=60,"D","F"))))
- Click Enter in the cell to get the result of the formula in the cell.
- Copy the formula for the rest of the cells in the column
The assigned letter grades appear in column C.
Explanation of the formula
=IF(B2>=90,”A”,IF(B2>=80,”B”,IF(B2>=70,”C”,IF(B2>=60,”D”,”F”))))
This formula evaluates the value in cell B2 and assigns an “A” if the value is 90 or greater, a “B” if the value is between 80 and 89, a “C” if the value is between 70 and 79, a “D” if the value is between 60 and 69, and an “F” if the value is less than 60.
Notice that it can be challenging to keep track of which parentheses go with which arguments in nested IF functions.
Therefore, as we enter the formula, Excel uses different colors for the parentheses at each level of the nested IF functions to make it easier to see which parts of the formula belong together.
Also read: How to use Excel If Statement with Multiple Conditions Range
Example #2: Use Multiple IF Statements to Calculate Commission Based on Sales Volume
Here’s the dataset showing the sales of specific salespeople in a particular month.
We want to use multiple IF statements to calculate the tiered commission for the salespeople based on their sales volume.
We proceed as follows:
- Select cell C2 and enter the following formula:
=IF(B2>=40000, B2*0.14,IF(B2>=20000,B2*0.12,IF(B2>=10000,B2*0.105,IF(B2>0,B2*0.08,0))))
- Press the Enter key to get the result of the formula.
- Double-click or drag the Fill Handle to copy the formula down the column.
The commission for each salesperson is displayed in column D.
Explanation of the formula
=IF(B2>=40000, B2*0.14,IF(B2>=20000,B2*0.12,IF(B2>=10000,B2*0.105,IF(B2>0,B2*0.08,0))))
This formula evaluates the value in cell B2 and then does the following:
- If the value in cell B2 is greater than or equal to 40,000, the figure is multiplied by 14% (0.14).
- If the figure in cell B2 is less than 40,000 but greater than or equal to 20,000, the value is multiplied by 12% (0.12).
- If the number in cell B2 is less than 20,000 but greater than or equal to 10,000, the figure is multiplied by 10.5% (0.105).
- If the value in cell B2 is less than 10,000 but greater than 0 (zero), the number is multiplied by 8% (0.08).
- If the value in cell B2 is 0 (zero), 0 (zero) is returned.
Example #3: Use Multiple IF Statements to Assign Sales Performance Rating Based On Sales Target Achievement
The following is a dataset showing regional sales data of a specific technology company in a particular year.
We want to use multiple IF statements to assign a sales performance rating to each region based on their sales target achievement.
We use the following steps:
- Select cell C2 and type in the below formula:
=IF(B2>500000, "Excellent", IF(B2>400000, "Good", IF(B2>275000, "Average", "Poor")))
- Click Enter on the Formula bar.
- Drag or double-click the Fill Handle to copy the formula down the column.
The performance ratings of the regions are shown in column C.
Explanation of the formula
=IF(B2>500000, “Excellent”, IF(B2>400000, “Good”, IF(B2>275000, “Average”, “Poor”)))
In this formula, if the sales target in cell B2 is greater than 500,000, the formula returns “Excellent.”
If it’s between 400,000 and 500,000, the formula returns “Good.”
If it’s between 275,000 and 400,000, the formula returns “Average.” And if it’s below 275,000, the formula returns “Poor.”
Example #4: Use Multiple IF Statements in Excel to Check For Errors and Return Error Messages
Suppose we have the following dataset of students’ English test scores. Some scores are less than 0 or greater than 100, and there are no scores in some cases.
We want to use nested IF statements to check for scores in column B and display error messages in column C if there are no scores or the scores are less than 0 or greater than 100.
If the score in column B is valid, we want the formula to return an empty string in column C.
Here are the steps to follow:
- Select cell C2 and enter the following formula:
=IF(OR(B2<0,B2>100),"Score out of range",IF(ISBLANK(B2),"Invalid score",""))
- Click Enter on the Formula bar.
- Drag the Fill Handle to copy the formula down the column.
The error messages are shown in column C.
Explanation of the formula
=IF(OR(B2<0,B2>100),”Score out of range”,IF(ISBLANK(B2),”Invalid score”,””))
This formula uses the OR function to check if the score in cell B2 is less than 0 or greater than 100, and if it is, it returns the error message “Score out of range.”
The formula also uses the ISBLANK function to check if cell B2 is blank, and if it is, it returns the error message “Invalid score.”
If there is no error, the formula returns an empty string, meaning no message is displayed in column B.
Alternatives to Using Multiple IF Statements in Excel
Formulas using nested IF statements can become difficult to read and manage if we have more than a few conditions to test.
In addition, if we exceed the maximum allowed limit of 64 nested IF statements, we will get an error message.
Fortunately, Excel offers alternative ways to use instead of nested IF functions, especially when we need to test more than a few conditions.
We present the alternative ways in this tutorial.
Alternative #1: Use the IFS Function
The IFS function tests whether one or more conditions are met and returns a value corresponding to the first TRUE condition.
Before the release of the IFS function in 2018 as part of the Excel 365 update, the only way to test multiple conditions and return a corresponding value in Excel was to use nested IF statements.
However, multiple IF statements have the downside of resulting in unwieldy formulas that are difficult to read and maintain.
In some situations, the IFS function is designed to replace the need for multiple IF functions.
The syntax of the IFS function is more straightforward and easier to read than nested IF statements, and it can handle up to 127 conditions.
Here’s an example:
Let’s consider the following dataset showing some students’ scores on a Math test.
We want to use the IFS function to assign letter grades to the students based on their scores.
We use the following steps:
- Select cell C2 and type in the below formula:
=IFS(B2>=90, "A", B2>=80, "B", B2>=70, "C", B2>=60, "D", B2<60, "F")
- Click Enter on the Formula bar.
- Drag or double-click the Fill Handle to copy the formula down the column.
The student’s letter grades are shown in column C.
Explanation of the formula
=IFS(B2>=90, “A”, B2>=80, “B”, B2>=70, “C”, B2>=60, “D”, B2<60, “F”)
This formula tests the score in cell B2 against each condition and returns the corresponding grade letter when the condition is true.
Limitation of IFS Function
The IFS function in Excel is designed to simplify complex nested IF statements.
However, there are situations where the IFS function may not be able to replace nested IF functions completely.
One such situation is when you must calculate or operate based on a condition or set of conditions.
While the IFS function can return a value or text string based on a condition, it cannot perform calculations or operations on that value like nested IF statements.
Another situation where the IFS function may be less useful is when you need to test for a range of conditions rather than just a specific set.
This is because the IFS function requires you to specify each condition and corresponding result separately, which can become cumbersome if you have many conditions to test—in contrast, nested IF statements allow you to test for a range of conditions using logical operators like AND and OR.
The IFS function is a powerful tool for simplifying complex logical tests in Excel.
However, there may be situations where nested IF statements are more appropriate for your needs.
We recommend that you consider both options and choose the one that best fits the specific requirements of your task.
Alternative #2: Use Nested IF Functions
We can use multiple IFS functions in a formula if we have more than one condition to test.
For example, let’s say we have the following dataset of student names and scores on a Physics test in columns A and B.
We want to assign a letter grade to each score and include a pass or fail designation based on whether the score is above or below 75.
Here are the steps to use:
- Select cell C2 and enter the following formula
=IFS(B2>=90,"A",B2>=80,"B",B2>=70,"C",B2>=60,"D",B2<60,"F")&" "&IFS(B2>=75,"Pass",B2<75,"Fail")
- Click Enter on the Formula bar.
- Drag or double-click the Fill Handle to copy the formula down the column.
The letter grade and designation of the student scores are displayed in column C.
Explanation of the formula
=IFS(B2>=90,”A”,B2>=80,”B”,B2>=70,”C”,B2>=60,”D”,B2<60,”F”)&” “&IFS(B2>=75,”Pass”,B2<75,”Fail”)
This formula uses the first IFS function to assign a letter grade based on the score in column A and the second IFS function to give a pass/fail designation based on the score in column A.
The two IFS functions are combined using the ampersand (&) operator to create a single text string that displays each score’s letter grade and pass/fail designation.
Alternative #3: Use the Combination of CHOOSE and XMATCH Functions
The CHOOSE function selects a value or action from a value list based on an index number.
The XMATCH function locates and returns the relative position of an item in an array. We can combine these functions in a formula instead of nested IF functions.
Here’s an example:
Suppose we have the following dataset showing some students’ scores and letter grades on a Biology test.
We want to use a formula combining the CHOOSE and XMATCH functions to assign corresponding grade points in column D to each letter grade.
We use the following steps:
- Select cell D2 and type in the below formula:
=CHOOSE(XMATCH(C2,{"F","E","D","C","B","A"},0),0,1,2,3,4,5)
- Click Enter on the Formula bar.
- Drag or double-click the Fill Handle to copy the formula down the column.
The grade points for each student are displayed in column D.
Explanation of the formula
=CHOOSE(XMATCH(C2,{“F”,”E”,”D”,”C”,”B”,”A”},0),0,1,2,3,4,5)
This formula applies the XMATCH function to find the position of the letter grade in the array {“F”,”E”,”D”,”C”,”B”,”A”}, and then uses the CHOOSE function to return the corresponding grade points.
Alternative #4: Use the VLOOKUP Function
The VLOOKUP function looks for a value in the leftmost column of a table and then returns a value in the same row from a specified column.
We can use the VLOOKUP function instead of nested IF functions in Excel.
The following is an example of using the VLOOKUP function instead of nested IF functions in Excel:
Suppose we have the following dataset showing some students’ scores and letter grades on a Biology test.
We want to use the VLOOKUP function to assign grade points to each student’s letter grade in column D.
We use the steps below:
- Create a table that lists the grades and their corresponding grade points in cell range F1:G7.
- In cell D2, type the following formula:
=VLOOKUP(C2,$F$2:$G$7,2,FALSE)
Note: Use the dollar signs to lock down the cell range F2:G7.
- Click Enter on the Formula bar.
- Drag or double-click the Fill Handle to copy the formula down the column.
The grade points for each student appear in column D.
Explanation of the formula
=VLOOKUP(C2,$F$2:$G$7,2,FALSE)
This formula uses the VLOOKUP function to look up the grade in cell C2 in the table in F2:G7 and return the corresponding grade point in the second column (i.e., column G).
The “FALSE” argument ensures that an exact match is required.
Alternative #5: Use a User-Defined Function
If you need to test more than a few conditions, consider creating a User Defined Function in VBA that can handle many conditions.
Here’s an example of using VBA code to replace nested IF functions in Excel:
Suppose we have the following dataset showing the sales of specific salespeople in a particular month.
We want to use a User Defined Function to calculate the commission for each salesperson based on the following rates:
- If the total sales are less than $10,000, the commission rate is 8%.
- If the total sales are equal to or greater than $10,000 but less than $20,000, the commission rate is 10.5%.
- If the total sales are equal to or greater than $20,000 but less than $40,000, the commission rate is 12%.
- If the sales are equal to or greater than $40,000, the commission rate is 14%
We use the following steps:
- Open the worksheet containing the sales dataset.
- Press Alt + F11 to launch the Visual Basic Editor.
- Click Insert on the menu bar and choose Module to insert a new module.
- Enter the following VBA code.
'Code developed by Steve Scott from https://spreadsheetplanet.com
Function COMMISSION(Sales As Double) As Double
Const Rate1 = 0.08
Const Rate2 = 0.105
Const Rate3 = 0.12
Const Rate4 = 0.14
'Calculate sales commissions
Select Case Sales
Case 0 To 9999.99: COMMISSION = Sales * Rate1
Case 10000 To 19999.99: COMMISSION = Sales * Rate2
Case 20000 To 39999.99: COMMISSION = Sales * Rate3
Case Is >= 40000: COMMISSION = Sales * Rate4
End Select
End Function
- Save the function procedure and the workbook as a Macro-Enabled Workbook.
- Press Alt + F11 to switch to the active worksheet with the sales dataset.
- Select cell C2 and enter the following formula:
=COMMISSION(B2)
- Click Enter on the Formula bar.
- Drag or double-click the Fill Handle to copy the formula down the column.
The commission for each salesperson is displayed in column C.
This VBA function takes the sales amount as an argument and returns the corresponding commission.
The User-Defined Function is a much simpler and easier-to-read solution than using nested IF functions.
This tutorial showed four examples of using nested IF statements in Excel and gave five alternatives to using multiple IF statements in Excel. We hope you found the tutorial helpful.
Other Excel tutorials you may find useful:
- Excel Logical Test Using Multiple If Statements in Excel [AND/OR]
- How to Compare Two Columns in Excel (using VLOOKUP & IF)
- Using IF Function with Dates in Excel (Easy Examples)
- COUNTIF Greater Than Zero in Excel
- BETWEEN Formula in Excel (Using IF Function) – Examples
- Count Cells Less than a Value in Excel (COUNTIF Less)
IF AND Excel Formula
The IF AND excel formula is the combination of two different logical functions often nested together that enables the user to evaluate multiple conditions using AND functions. Based on the output of the AND function, the IF function returns either the “true” or “false” value, respectively.
- The IF formula in ExcelIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
read more is used to test and compare the conditions expressed with the expected value. It is used to test a single criterion. - The logical AND formula is used to test multiple criteria. It returns “true” if all the conditions mentioned are satisfied, or else returns “false.” It tests more than one criterion and accordingly returns an output. It can also be used along with the IF formula to return the desired result.
Table of contents
- IF AND Excel Formula
- Syntax
- How to Use IF AND Excel Statement?
- Example #1
- Example #2
- Example #3
- The Characteristics of IF AND function
- Frequently Asked Questions
- Recommended Articles
Syntax
The IF AND formula can be applied as follows:
“=IF(AND (Condition 1,Condition 2,…),Value _if _True,Value _if _False)”
How to Use IF AND Excel Statement?
You can download this IF AND Formula Excel Template here – IF AND Formula Excel Template
Let us understand the usage of the IF AND formula with the help of some examples mentioned below:
Example #1
The table given below provides a list of apartments along with their age (in years) and type of society. Now we need to perform a comparative analysis for the apartments based on the age of the building and the type of society.
Here, we use the combination of less than equal (<=) to operator and the equal to (=) text functions in the condition to be demonstrated for IF AND function.
- The IF AND formula used to perform the analysis is stated as follows:
“=IF(AND(B2<=2,C2=“Gated”),“Consider”, “”)”
- The succeeding image shows the IF AND condition applied to perform the evaluation.
- Press “Enter” to get the answer.
- Drag the formula to find the results for all the apartments.
The results in the cell D of the above table shows that the IF AND formula will be performing one among the following:
- If both the arguments entered in the AND function is “true,” then the IF function will return that apartment to be “Consider.”
- If either of the arguments in the AND functionThe AND function in Excel is classified as a logical function; it returns TRUE if the specified conditions are met, otherwise it returns FALSE.read more is “false” or both the arguments entered are “false,” then the IF function will return a blank string.
The IF AND formula can also perform calculations based on whether the AND function returns “true” or “false,” apart from returning only the predefined text strings.
We will understand this concept with the help of the below-mentioned example.
Example #2
The given data tableA data table in excel is a type of what-if analysis tool that allows you to compare variables and see how they impact the result and overall data. It can be found under the data tab in the what-if analysis section.read more has the list of employee name along with their orders received, performance, and salaries. Calculate the employee hike (or bonus) based on two parameters–the number of orders received and performance.
The criteria to calculate the bonus is as follows.
- The number of orders received is greater than or equal to 200, and the performance is equal to “A.”
- The IF AND formula will be,
“=IF(AND(B2>=200,C2= “A”),D2*10%,D2*5%)”
- Press “Enter” to get the final output. The bonus appears in cell E2.
- Drag the formula to find the bonus of all employees.
Based on these results, the IF formula does the following evaluation:
- If both the conditions are satisfied, the AND function returns “true,” then the bonus received is calculated as salary multiplied by 10%.
- If either one or both the conditions are found to be “false” by the AND function, then the bonus is calculated as salary multiplied by 5%.
Examples 1 and 2 have only two criteria to test and evaluate. Using multiple arguments or conditions to test them for “true” or “false” is also allowed.
Example #3
Let us evaluate multiple criteria and use AND function.
A table with five stocks and their parameter details including financial ratiosFinancial ratios are indications of a company’s financial performance. There are several forms of financial ratios that indicate the company’s results, financial risks, and operational efficiency, such as the liquidity ratio, asset turnover ratio, operating profitability ratios, business risk ratios, financial risk ratio, stability ratios, and so on.read more, such as ROCEReturn on Capital Employed (ROCE) is a metric that analyses how effectively a company uses its capital and, as a result, indicates long-term profitability. ROCE=EBIT/Capital Employed.read more, ROEReturn on Equity (ROE) represents financial performance of a company. It is calculated as the net income divided by the shareholders equity. ROE signifies the efficiency in which the company is using assets to make profit.read more, Debt to equityThe debt to equity ratio is a representation of the company’s capital structure that determines the proportion of external liabilities to the shareholders’ equity. It helps the investors determine the organization’s leverage position and risk level. read more, and PE ratioThe price to earnings (PE) ratio measures the relative value of the corporate stocks, i.e., whether it is undervalued or overvalued. It is calculated as the proportion of the current price per share to the earnings per share. read more is provided (shown in the below table). Using this data lets us test the condition to invest in suitable stocks. That is, using the parameters, let us analyze the stocks to derive the best investment horizonThe term «investment horizon» refers to the amount of time an investor is expected to hold an investment portfolio or a security before selling it. Depending on the need for funds and risk appetite, the investor may invest for a few days or hours to a few years or decades.read more, which is important for growth.
The following syntax is used where the conditions are applied to arrive at the result (shown in the below table).
“=IF(AND(B2>18%,C2>20%,D2<2,E2<30%),“Invest”,“”)”
- Press “Enter” to get the final output (Investment Criteria) of the above formula.
- Drag the formula to find the Investment Criteria.
In the above data table, the AND function tests for the parameters using the operators. The resulting output generated by the IF formula is as follows:
- If all the four criteria mentioned in the AND function are tested and satisfied, then the IF function returns the “Invest” text string.
- If either one or more among the four conditions or all the four conditions fail to satisfy the AND function, then the IF function returns empty strings (“”).
The Characteristics of IF AND function
- The IF AND function does not differentiate between case-insensitive texts.
- The AND function can be used to evaluate up to 255 conditions for “true” or “false,” and the total formula length does not exceed 8192 characters.
- Text values or blank cells are given as an argument to test the conditions in AND function.
- The AND formula will return “#VALUE!” if there is no logical output found while evaluating the conditions.
- IF AND excel statement is a combination of two logical functions that tests and evaluates multiple conditions.
- The output of the AND function is based on, whether the IF function will return the value “true” or “false,” respectively.
- IF function is used to test a single criterion whereas, the AND function is used to test multiple criteria.
- The syntax of the IF AND formula is:
“=IF(AND (Condition 1,Condition 2,…),Value _if _True,Value _if _False)”
- The IF AND formula also performs a calculation based on whether the AND function is “true” or “false” apart from returning only the predefined text strings.
Frequently Asked Questions
1. How to use IF AND function in Excel?
The IF AND excel statement is the two logical functions often nested together.
Syntax:
“=IF(AND(Condition1,Condition2, value_if_true,vaue_if_false)”
The IF formula is used to test and compare the conditions expressed, along with the expected value. It provides the desired result if the condition is either “true” or “false.”
The AND formula is used to test multiple criteria. It returns “true” if all the given conditions are satisfied, or else returns “false.”
2. What is the IF AND function in Excel?
IF AND formula is applied as the combination of the two logical functions that enable the user to evaluate the multiple conditions. Based on the output of the AND function, the IF function returns the output “true” or “false.”
3. How to combine IF and AND functions in Excel?
To combine IF and AND functions, you need to replace the “condition_test” argument in the IF function with AND function.
“=IF(condition_test, value_if_true,vaue_if_false)”
“=IF(AND(Condition1,Condition2, value_if_true,vaue_if_false)”
In AND function we can use multiple conditions.
Recommended Articles
This has been a guide to IF AND function in Excel. Here we discuss how to use IF Formula combined with AND function along with examples and downloadable templates. You may also look at these useful functions in Excel –
- IF EXCEL FunctionIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
read more - Average IF Function
- SUMIF with Multiple CriteriaThe SUMIF (SUM+IF) with multiple criteria sums the cell values based on the conditions provided. The criteria are based on dates, numbers, and text. The SUMIF function works with a single criterion, while the SUMIFS function works with multiple criteria in excel.read more
- Nested If ConditionIn Excel, nested if function means using another logical or conditional function with the if function to test multiple conditions. For example, if there are two conditions to be tested, we can use the logical functions AND or OR depending on the situation, or we can use the other conditional functions to test even more ifs inside a single if.read more
На чтение 2 мин
Функция AND (И) в Excel используется для сравнения нескольких условий.
Содержание
- Что возвращает функция
- Синтаксис
- Аргументы функции
- Дополнительная информация
- Примеры использования функции AND (И, ИЛИ) в Excel
Что возвращает функция
Возвращает TRUE если значение или условие, при сравнении, соответствует критериям заданным в функции, или FALSE, в случае, если условие не соответствует критериям.
Синтаксис
=AND(logical1, [logical2],…) — английская версия
=И(логическое_значение1;[логическое_значение2];…) — русская версия
Аргументы функции
- logical1 (логическое_значение1) — первое условие, которое вы хотите оценить с помощью функции;
- [logical2] ([логическое_значение2]) (не обязательно) — второе условие, которое вы хотите оценить с помощью функции.
Дополнительная информация
- Функция может быть использована совместно с другими формулами;
- Например, с помощью функции IF (ЕСЛИ) вы можете проверить условие, а затем указать значение, когда оно TRUE, и значение, когда оно равно FALSE. Использование функции AND (И) вместе с функцией IF (ЕСЛИ) позволяет тестировать несколько условий за один раз;
Например, если вы хотите проверить значение в ячейке A1 на предмет того, больше оно чем «0» или меньше чем «100», то вы можете использовать следующую формулу:
=IF(AND(A1>0,A1<100),”Approve”,”Reject”) — английская версия
Больше лайфхаков в нашем Telegram Подписаться
=ЕСЛИ(И(A1>0;A1<100);»Одобрить»;»Против») — русская версия
- Аргументы функции должны быть логически вычислимы по принципу (TRUE/FALSE);
- Ячейки с пустыми или текстовыми значениями игнорируются функцией;
- Если в качестве аргументов функции не указаны логически вычислимые данные, то функция выдаст ошибку #VALUE!;
- Одновременно вы можете тестировать до 255 условий в рамках одного использования функции.
Примеры использования функции AND (И, ИЛИ) в Excel
This post will guide you how to use IF function combining with AND logical function in Excel.
If you want to check if a value in cell match two or more conditions at the same time, if the test is TRUE, then you can take certain action. You can use the IF function combining with AND function to construct a condition statement. If the test is FALSE, then take another action.
Table of Contents
- Excel formula using IF & AND function
- Related Formulas
- Related Functions
The syntax of AND function in excel is as follow:
=AND(condition1,[condition2],...)
The Excel AND function returns TRUE if all of arguments are TRUE, and it returns FALSE if any of arguments are FALSE.
Now we want to check the results of two exam scores where the first score in cell A1 is greater than or equal to 60 AND the second score in cell B1 is greater than or equal to 80. If both conditions are TRUE, then returns the text of “good”, and if FALSE returns “bad”. Based on the above logic, we can write down the below IF formula:
=IF(AND(A1=60,B1=80),"good","bad")
We can enter the above formula into cell D1, and then drag the Fill Handle to the range D1:D3.it will apply for the other cells for this formula.
The logic test will check the two different cells in the above IF formula, if we can run two or more tests on the same cell. Of course yes, for example, if you want to check cell A1 if the value in cell A1 is greater than 60 but less than or equal to 70. If the test is TRUE, then take one action.
The logical test we can use for above logic as below:
=AND(A1>60, A1<=70)
IF formula:
=IF(AND(A1>60,A1<=70),”good”,””)
In this formula, if the test is FALSE, we just add an empty string (“”), IF the test is TRUE, the test string of “good” will appear.
Note: The AND function will check all test conditions in excel, even if one of the already tested conditions has a value of FALSE. This behavior is different with other programming languages. If any previous test conditions return FALSE, the subsequent conditions will not be tested.
For example: If the value of Cell B1 is 0, then the below IF&AND formula will return error message as “Divide by Zero Error”.
=IF(AND(B1<>0,(1/B1)>0.2),”A”,”D”))
As mentioned above, the AND function will check all conditions. To avoid this issue, we can use a nested IF function and check if the value of Cell B1 is not equal to 0 in the first IF statement.
The nested if formula is as below:
=IF(B1<>0,IF((1/B1>0.2),”A”,”D”))
- Excel IF formula with equal to logical operator
The “Equal to” logical operator can be used to compare the below data types, such as: text string, numbers, dates, Booleans. This section will guide you how to use “equal to” logical operator in excel IF formula with text string value and dates value… - Excel IF formula with OR logical function
If you want to check if one of several conditions is met in your excel workbook, if the test is TRUE, then you can take certain action. You can use the IF function combining with OR function to construct a condition statement… - Excel IF formula with AND & OR logical functions
If you want to test the result of cells based on several sets of multiple test conditions, you can use the IF function with the AND and OR functions at a time…
- Excel AND function
The Excel AND function returns TRUE if all of arguments are TRUE, and it returns FALSE if any of arguments are FALSE.The syntax of the AND function is as below:= AND (condition1,[condition2],…) … - Excel IF function
The Excel IF function perform a logical test to return one value if the condition is TRUE and return another value if the condition is FALSE…. - Excel nested if function
The nested IF function is formed by multiple if statements within one Excel if function. This excel nested if statement makes it possible for a single formula to take multiple actions…
I need to write an «if» statement in Excel based on text in two different cells.
If E2 ='in play' and F2 ='closed' output 3
If E2= 'in play' and F2 ='suspended' output 2
If E2 ='In Play' and F2 ='Null' output 1
If E2 ='Pre-Play' and F2 ='Null' output -1
If E2 ='Completed' and F2 ='Closed' output 2
If E2 ='Suspended' and F2 ='Null' output 3
If anything else output -2
where Null is no value in the cell
I was trying to do this with the code below but I can’t seem to get two or more IF AND statements working together. How can I solve this problem?
=IF(AND(E2="In Play",F2="Closed"),3, -2), IF(AND(E2="In Play",F2=" Suspended"),3,-2)
asked Apr 2, 2013 at 0:08
Consider that you have multiple «tests», e.g.,
- If E2 = ‘in play’ and F2 = ‘closed’, output 3
- If E2 = ‘in play’ and F2 = ‘suspended’, output 2
- Etc.
What you really need to do is put successive tests in the False
argument. You’re presently trying to separate each test by a comma, and that won’t work.
Your first three tests can all be joined in one expression like:
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))))
Remembering that each successive test needs to be the nested FALSE argument of the preceding test, you can do this:
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-Play",F2="Null"),-1,IF(AND(E2="completed",F2="closed"),2,IF(AND(E2="suspended",F2="Null"),3,-2))))
answered Apr 2, 2013 at 0:37
David ZemensDavid Zemens
52.8k11 gold badges79 silver badges129 bronze badges
2
With your ANDs you shouldn’t have a FALSE value -2, until right at the end, e.g. with just 2 ANDs
=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))
although it might be better with a combination of nested IFs and ANDs — try like this for the full formula:[Edited — thanks David]
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))
To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula
=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))
answered Apr 2, 2013 at 0:30
barry houdinibarry houdini
45.5k8 gold badges63 silver badges80 bronze badges
Try the following:
=IF(OR(E2="in play",E2="pre play",E2="complete",E2="suspended"),
IF(E2="in play",IF(F2="closed",3,IF(F2="suspended",2,IF(ISBLANK(F2),1,-2))),
IF(E2="pre play",IF(ISBLANK(F2),-1,-2),IF(E2="completed",IF(F2="closed",2,-2),
IF(E2="suspended",IF(ISBLANK(F2),3,-2))))),-2)
uvesten
3,3452 gold badges28 silver badges40 bronze badges
answered Mar 19, 2014 at 13:35
Making these 2 communicate
=IF(OR(AND(MID(K27,6,1)="N",(MID(K27,6,1)="C"),(MID(K27,6,1)="H"),(MID(K27,6,1)="I"),(MID(K27,6,1)="B"),(MID(K27,6,1)="F"),(MID(K27,6,1)="L"),(MID(K27,6,1)="M"),(MID(K27,6,1)="P"),(MID(K27,6,1)="R"),(MID(K27,6,1)="P"),ISTEXT(G27)="61"),AND(RIGHT(K27,2)=G27)),"Good","Review")
=IF(AND(RIGHT(K27,2)=G27),"Good","Review")
miken32
41.4k16 gold badges111 silver badges152 bronze badges
answered Jan 26, 2017 at 22:35
0
Как использовать функцию 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, упомянутая в этой статье. Будьте в курсе этих новых дополнений, вы будете впереди толпы.