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.
Syntax
IF(logical_test, value_if_true, [value_if_false])
For example:
-
=IF(A2>B2,»Over Budget»,»OK»)
-
=IF(A2=B2,B4-A4,»»)
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. |
Remarks
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.
-
=IF(D2>89,»A»,IF(D2>79,»B»,IF(D2>69,»C»,IF(D2>59,»D»,»F»))))
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:
-
=IF(B2>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»))))))))))))
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.
-
=IF(C9>15000,20%,IF(C9>12500,17.5%,IF(C9>10000,15%,IF(C9>7500,12.5%,IF(C9>5000,10%,0)))))
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:
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:
-
=VLOOKUP(C2,C5:D17,2,TRUE)
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.
-
=VLOOKUP(B9,B2:C6,2,TRUE)
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:
-
=IF(D2>89,»A»,IF(D2>79,»B»,IF(D2>69,»C»,IF(D2>59,»D»,»F»))))
It can be made much simpler with a single IFS function:
-
=IFS(D2>89,»A»,D2>79,»B»,D2>69,»C»,D2>59,»D»,TRUE,»F»)
The IFS function is great because you don’t need to worry about all of those IF statements and parentheses.
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
Related Topics
Video: Advanced IF functions
IFS function (Microsoft 365, Excel 2016 and later)
The COUNTIF function will count values based on a single criteria
The COUNTIFS function will count values based on multiple criteria
The SUMIF function will sum values based on a single criteria
The SUMIFS function will sum values based on multiple criteria
AND function
OR function
VLOOKUP function
Overview of formulas in Excel
How to avoid broken formulas
Detect errors in formulas
Logical functions
Excel functions (alphabetical)
Excel functions (by category)
Содержание
- Using IF with AND, OR and NOT functions
- Examples
- Using AND, OR and NOT with Conditional Formatting
- Need more help?
- See also
- Функция ЕСЛИ в Excel. Как использовать?
- Что возвращает функция
- Синтаксис
- Аргументы функции
- Дополнительная информация
- Функция Если в Excel примеры с несколькими условиями
- Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)
- Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения
- Пример 3. Вычисляем сумму комиссии с продаж с помощью функции IF (ЕСЛИ) в Excel
- Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel
- Пример 5. Преобразуем ошибки в значения “0” с помощью функции IF (ЕСЛИ)
- 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
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.
Источник
Функция ЕСЛИ в Excel. Как использовать?
Функция ЕСЛИ в Excel — это отличный инструмент для проверки условий на ИСТИНУ или ЛОЖЬ. Если значения ваших расчетов равны заданным параметрам функции как ИСТИНА, то она возвращает одно значение, если ЛОЖЬ, то другое.
Что возвращает функция
Заданное вами значение при выполнении двух условий ИСТИНА или ЛОЖЬ.
Синтаксис
=IF(logical_test, [value_if_true], [value_if_false]) — английская версия
=ЕСЛИ(лог_выражение; [значение_если_истина]; [значение_если_ложь]) — русская версия
Аргументы функции
- logical_test (лог_выражение) — это условие, которое вы хотите протестировать. Этот аргумент функции должен быть логичным и определяемым как ЛОЖЬ или ИСТИНА. Аргументом может быть как статичное значение, так и результат функции, вычисления;
- [value_if_true] ([значение_если_истина]) — (не обязательно) — это то значение, которое возвращает функция. Оно будет отображено в случае, если значение которое вы тестируете соответствует условию ИСТИНА;
- [value_if_false] ([значение_если_ложь]) — (не обязательно) — это то значение, которое возвращает функция. Оно будет отображено в случае, если условие, которое вы тестируете соответствует условию ЛОЖЬ.
Дополнительная информация
- В функции ЕСЛИ может быть протестировано 64 условий за один раз;
- Если какой-либо из аргументов функции является массивом — оценивается каждый элемент массива;
- Если вы не укажете условие аргумента FALSE (ЛОЖЬ) value_if_false (значение_если_ложь) в функции, т.е. после аргумента value_if_true (значение_если_истина) есть только запятая (точка с запятой), функция вернет значение “0”, если результат вычисления функции будет равен FALSE (ЛОЖЬ).
На примере ниже, формула =IF(A1> 20,”Разрешить”) или =ЕСЛИ(A1>20;»Разрешить») , где value_if_false (значение_если_ложь) не указано, однако аргумент value_if_true (значение_если_истина) по-прежнему следует через запятую. Функция вернет “0” всякий раз, когда проверяемое условие не будет соответствовать условиям TRUE (ИСТИНА).|
- Если вы не укажете условие аргумента TRUE(ИСТИНА) (value_if_true (значение_если_истина)) в функции, т.е. условие указано только для аргумента value_if_false (значение_если_ложь), то формула вернет значение “0”, если результат вычисления функции будет равен TRUE (ИСТИНА);
На примере ниже формула равна = IF (A1>20;«Отказать») или =ЕСЛИ(A1>20;»Отказать») , где аргумент value_if_true (значение_если_истина) не указан, формула будет возвращать “0” всякий раз, когда условие соответствует TRUE (ИСТИНА).
Функция Если в Excel примеры с несколькими условиями
Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)
При использовании функции ЕСЛИ в Excel, вы можете использовать различные операторы для проверки состояния. Вот список операторов, которые вы можете использовать:
Ниже приведен простой пример использования функции при расчете оценок студентов. Если сумма баллов больше или равна «35», то формула возвращает “Сдал”, иначе возвращается “Не сдал”.
Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения
Функция может принимать до 64 условий одновременно. Несмотря на то, что создавать длинные вложенные функции нецелесообразно, то в редких случаях вы можете создать формулу, которая множество условий последовательно.
В приведенном ниже примере мы проверяем два условия.
- Первое условие проверяет, сумму баллов не меньше ли она чем 35 баллов. Если это ИСТИНА, то функция вернет “Не сдал”;
- В случае, если первое условие — ЛОЖЬ, и сумма баллов больше 35, то функция проверяет второе условие. В случае если сумма баллов больше или равна 75. Если это правда, то функция возвращает значение “Отлично”, в других случаях функция возвращает “Сдал”.
Пример 3. Вычисляем сумму комиссии с продаж с помощью функции IF (ЕСЛИ) в Excel
Функция позволяет выполнять вычисления с числами. Хороший пример использования — расчет комиссии продаж для торгового представителя.
В приведенном ниже примере, торговый представитель по продажам:
- не получает комиссионных, если объем продаж меньше 50 тыс;
- получает комиссию в размере 2%, если продажи между 50-100 тыс
- получает 4% комиссионных, если объем продаж превышает 100 тыс.
Рассчитать размер комиссионных для торгового агента можно по следующей формуле:
=ЕСЛИ(B2 — русская версия
В формуле, использованной в примере выше, вычисление суммы комиссионных выполняется в самой функции ЕСЛИ . Если объем продаж находится между 50-100K, то формула возвращает B2 * 2%, что составляет 2% комиссии в зависимости от объема продажи.
Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel
Вы можете использовать логические операторы (AND/OR) (И/ИЛИ) внутри функции для одновременного тестирования нескольких условий.
Например, предположим, что вы должны выбрать студентов для стипендий, основываясь на оценках и посещаемости. В приведенном ниже примере учащийся имеет право на участие только в том случае, если он набрал более 80 баллов и имеет посещаемость более 80%.
Вы можете использовать функцию AND (И) вместе с функцией IF (ЕСЛИ) , чтобы сначала проверить, выполняются ли оба эти условия или нет. Если условия соблюдены, функция возвращает “Имеет право”, в противном случае она возвращает “Не имеет право”.
Формула для этого расчета:
=IF(AND(B2>80,C2>80%),”Да”,”Нет”) — английская версия
=ЕСЛИ(И(B2>80;C2>80%);»Да»;»Нет») — русская версия
Пример 5. Преобразуем ошибки в значения “0” с помощью функции IF (ЕСЛИ)
С помощью этой функции вы также можете убирать ячейки содержащие ошибки. Вы можете преобразовать значения ошибок в пробелы или нули или любое другое значение.
Формула для преобразования ошибок в ячейках следующая:
=IF(ISERROR(A1),0,A1) — английская версия
=ЕСЛИ(ЕОШИБКА(A1);0;A1) — русская версия
Формула возвращает “0”, в случае если в ячейке есть ошибка, иначе она возвращает значение ячейки.
ПРИМЕЧАНИЕ. Если вы используете Excel 2007 или версии после него, вы также можете использовать функцию IFERROR для этого.
Точно так же вы можете обрабатывать пустые ячейки. В случае пустых ячеек используйте функцию ISBLANK, на примере ниже:
=IF(ISBLANK(A1),0,A1) — английская версия
=ЕСЛИ(ЕПУСТО(A1);0;A1) — русская версия
Источник
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.
Источник
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)
This Excel tutorial explains how to use the Excel IF function with syntax and examples.
Description
The Microsoft Excel IF function returns one value if the condition is TRUE, or another value if the condition is FALSE.
The IF function is a built-in function in Excel that is categorized as a Logical Function. It can be used as a worksheet function (WS) in Excel. As a worksheet function, the IF function can be entered as part of a formula in a cell of a worksheet.
Subscribe
If you want to follow along with this tutorial, download the example spreadsheet.
Download Example
Syntax
The syntax for the IF function in Microsoft Excel is:
IF( condition, value_if_true, [value_if_false] )
Parameters or Arguments
- condition
- The value that you want to test.
- value_if_true
- It is the value that is returned if condition evaluates to TRUE.
- value_if_false
- Optional. It is the value that is returned if condition evaluates to FALSE.
Returns
The IF function returns value_if_true when the condition is TRUE.
The IF function returns value_if_false when the condition is FALSE.
The IF function returns FALSE if the value_if_false parameter is omitted and the condition is FALSE.
Example (as Worksheet Function)
Let’s explore how to use the IF function as a worksheet function in Microsoft Excel.
Based on the Excel spreadsheet above, the following IF examples would return:
=IF(B2<10, "Reorder", "") Result: "Reorder" =IF(A2="Apples", "Equal", "Not Equal") Result: "Equal" =IF(B3>=20, 12, 0) Result: 12
Combining the IF function with Other Logical Functions
Quite often, you will need to specify more complex conditions when writing your formula in Excel. You can combine the IF function with other logical functions such as AND, OR, etc. Let’s explore this further.
AND function
The IF function can be combined with the AND function to allow you to test for multiple conditions. When using the AND function, all conditions within the AND function must be TRUE for the condition to be met. This comes in very handy in Excel formulas.
Based on the spreadsheet above, you can combine the IF function with the AND function as follows:
=IF(AND(A2="Anderson",B2>80), "MVP", "regular") Result: "MVP" =IF(AND(B2>=80,B2<=100), "Great Score", "Not Bad") Result: "Great Score" =IF(AND(B3>=80,B3<=100), "Great Score", "Not Bad") Result: "Not Bad" =IF(AND(A2="Anderson",A3="Smith",A4="Johnson"), 100, 50) Result: 100 =IF(AND(A2="Anderson",A3="Smith",A4="Parker"), 100, 50) Result: 50
In the examples above, all conditions within the AND function must be TRUE for the condition to be met.
OR function
The IF function can be combined with the OR function to allow you to test for multiple conditions. But in this case, only one or more of the conditions within the OR function needs to be TRUE for the condition to be met.
Based on the spreadsheet above, you can combine the IF function with the OR function as follows:
=IF(OR(A2="Apples",A2="Oranges"), "Fruit", "Other") Result: "Fruit" =IF(OR(A4="Apples",A4="Oranges"),"Fruit","Other") Result: "Other" =IF(OR(A4="Bananas",B4>=100), 999, "N/A") Result: 999 =IF(OR(A2="Apples",A3="Apples",A4="Apples"), "Fruit", "Other") Result: "Fruit"
In the examples above, only one of the conditions within the OR function must be TRUE for the condition to be met.
Let’s take a look at one more example that involves ranges of percentages.
Based on the spreadsheet above, we would have the following formula in cell D2:
=IF(OR(B2>=5%,B2<=-5%),"investigate","") Result: "investigate"
This IF function would return «investigate» if the value in cell B2 was either below -5% or above 5%. Since -6% is below -5%, it will return «investigate» as the result. We have copied this formula into cells D3 through D9 to show you the results that would be returned.
For example, in cell D3, we would have the following formula:
=IF(OR(B3>=5%,B3<=-5%),"investigate","") Result: "investigate"
This formula would also return «investigate» but this time, it is because the value in cell B3 is greater than 5%.
Frequently Asked Questions
Question: In Microsoft Excel, I’d like to use the IF function to create the following logic:
if C11>=620, and C10=»F»or»S», and C4<=$1,000,000, and C4<=$500,000, and C7<=85%, and C8<=90%, and C12<=50, and C14<=2, and C15=»OO», and C16=»N», and C19<=48, and C21=»Y», then reference cell A148 on Sheet2. Otherwise, return an empty string.
Answer: The following formula would accomplish what you are trying to do:
=IF(AND(C11>=620, OR(C10="F",C10="S"), C4<=1000000, C4<=500000, C7<=0.85, C8<=0.9, C12<=50, C14<=2, C15="OO", C16="N", C19<=48, C21="Y"), Sheet2!A148, "")
Question: In Microsoft Excel, I’m trying to use the IF function to return 0 if cell A1 is either < 150,000 or > 250,000. Otherwise, it should return A1.
Answer: You can use the OR function to perform an OR condition in the IF function as follows:
=IF(OR(A1<150000,A1>250000),0,A1)
In this example, the formula will return 0 if cell A1 was either less than 150,000 or greater than 250,000. Otherwise, it will return the value in cell A1.
Question: In Microsoft Excel, I’m trying to use the IF function to return 25 if cell A1 > 100 and cell B1 < 200. Otherwise, it should return 0.
Answer: You can use the AND function to perform an AND condition in the IF function as follows:
=IF(AND(A1>100,B1<200),25,0)
In this example, the formula will return 25 if cell A1 is greater than 100 and cell B1 is less than 200. Otherwise, it will return 0.
Question: In Microsoft Excel, I need to write a formula that works this way:
IF (cell A1) is less than 20, then times it by 1,
IF it is greater than or equal to 20 but less than 50, then times it by 2
IF its is greater than or equal to 50 and less than 100, then times it by 3
And if it is great or equal to than 100, then times it by 4
Answer: You can write a nested IF statement to handle this. For example:
=IF(A1<20, A1*1, IF(A1<50, A1*2, IF(A1<100, A1*3, A1*4)))
Question: In Microsoft Excel, I need a formula in cell C5 that does the following:
IF A1+B1 <= 4, return $20
IF A1+B1 > 4 but <= 9, return $35
IF A1+B1 > 9 but <= 14, return $50
IF A1+B1 >= 15, return $75
Answer: In cell C5, you can write a nested IF statement that uses the AND function as follows:
=IF((A1+B1)<=4,20,IF(AND((A1+B1)>4,(A1+B1)<=9),35,IF(AND((A1+B1)>9,(A1+B1)<=14),50,75)))
Question: In Microsoft Excel, I need a formula that does the following:
IF the value in cell A1 is BLANK, then return «BLANK»
IF the value in cell A1 is TEXT, then return «TEXT»
IF the value in cell A1 is NUMERIC, then return «NUM»
Answer: You can write a nested IF statement that uses the ISBLANK function, the ISTEXT function, and the ISNUMBER function as follows:
=IF(ISBLANK(A1)=TRUE,"BLANK",IF(ISTEXT(A1)=TRUE,"TEXT",IF(ISNUMBER(A1)=TRUE,"NUM","")))
Question: In Microsoft Excel, I want to write a formula for the following logic:
IF R1<0.3 AND R2<0.3 AND R3<0.42 THEN «OK» OTHERWISE «NOT OK»
Answer: You can write an IF statement that uses the AND function as follows:
=IF(AND(R1<0.3,R2<0.3,R3<0.42),"OK","NOT OK")
Question: In Microsoft Excel, I need a formula for the following:
IF cell A1= PRADIP then value will be 100
IF cell A1= PRAVIN then value will be 200
IF cell A1= PARTHA then value will be 300
IF cell A1= PAVAN then value will be 400
Answer: You can write an IF statement as follows:
=IF(A1="PRADIP",100,IF(A1="PRAVIN",200,IF(A1="PARTHA",300,IF(A1="PAVAN",400,""))))
Question: In Microsoft Excel, I want to calculate following using an «if» formula:
if A1<100,000 then A1*.1% but minimum 25
and if A1>1,000,000 then A1*.01% but maximum 5000
Answer: You can write a nested IF statement that uses the MAX function and the MIN function as follows:
=IF(A1<100000,MAX(25,A1*0.1%),IF(A1>1000000,MIN(5000,A1*0.01%),""))
Question: In Microsoft Excel, I am trying to create an IF statement that will repopulate the data from a particular cell if the data from the formula in the current cell equals 0. Below is my attempt at creating an IF statement that would populate the data; however, I was unsuccessful.
=IF(IF(ISERROR(M24+((L24-S24)/AA24)),"0",M24+((L24-S24)/AA24)))=0,L24)
The initial part of the formula calculates the EAC (Estimate At completion = AC+(BAC-EV)/CPI); however if the current EV (Earned Value) is zero, the EAC will equal zero. IF the outcome is zero, I would like the BAC (Budget At Completion), currently recorded in another cell (L24), to be repopulated in the current cell as the EAC.
Answer: You can write an IF statement that uses the OR function and the ISERROR function as follows:
=IF(OR(S24=0,ISERROR(M24+((L24-S24)/AA24))),L24,M24+((L24-S24)/AA24))
Question: I have been looking at your Excel IF, AND and OR sections and found this very helpful, however I cannot find the right way to write a formula to express if C2 is either 1,2,3,4,5,6,7,8,9 and F2 is F and F3 is either D,F,B,L,R,C then give a value of 1 if not then 0. I have tried many formulas but just can’t get it right, can you help please?
Answer: You can write an IF statement that uses the AND function and the OR function as follows:
=IF(AND(C2>=1,C2<=9, F2="F",OR(F3="D",F3="F",F3="B",F3="L",F3="R",F3="C")),1,0)
Question:In Excel, I have a roadspeed of a car in m/s in cell A1 and a drop down menu of different units in C1 (which unclude mph and kmh). I have used the following IF function in B1 to convert the number to the unit selected from the dropdown box:
=IF(C1="mph","=A1*2.23693629",IF(C1="kmh","A1*3.6"))
However say if kmh was selected B1 literally just shows A1*3.6 and does not actually calculate it. Is there away to get it to calculate it instead of just showing the text message?
Answer: You are very close with your formula. Because you are performing mathematical operations (such as A1*2.23693629 and A1*3.6), you do not need to surround the mathematical formulas in quotes. Quotes are necessary when you are evaluating strings, not performing math.
Try the following:
=IF(C1="mph",A1*2.23693629,IF(C1="kmh",A1*3.6))
Question:For an IF statement in Excel, I want to combine text and a value.
For example, I want to put an equation for work hours and pay. IF I am paid more than I should be, I want it to read how many hours I owe my boss. But if I work more than I am paid for, I want it to read what my boss owes me (hours*Pay per Hour).
I tried the following:
=IF(A2<0,"I owe boss" abs(A2) "Hours","Boss owes me" abs(A2)*15 "dollars")
Is it possible or do I have to do it in 2 separate cells? (one for text and one for the value)
Answer: There are two ways that you can concatenate text and values. The first is by using the & character to concatenate:
=IF(A2<0,"I owe boss " & ABS(A2) & " Hours","Boss owes me " & ABS(A2)*15 & " dollars")
Or the second method is to use the CONCATENATE function:
=IF(A2<0,CONCATENATE("I owe boss ", ABS(A2)," Hours"), CONCATENATE("Boss owes me ", ABS(A2)*15, " dollars"))
Question:I have Excel 2000. IF cell A2 is greater than or equal to 0 then add to C1. IF cell B2 is greater than or equal to 0 then subtract from C1. IF both A2 and B2 are blank then equals C1. Can you help me with the IF function on this one?
Answer: You can write a nested IF statement that uses the AND function and the ISBLANK function as follows:
=IF(AND(ISBLANK(A2)=FALSE,A2>=0),C1+A2, IF(AND(ISBLANK(B2)=FALSE,B2>=0),C1-B2, IF(AND(ISBLANK(A2)=TRUE, ISBLANK(B2)=TRUE),C1,"")))
Question:How would I write this equation in Excel? IF D12<=0 then D12*L12, IF D12 is > 0 but <=600 then D12*F12, IF D12 is >600 then ((600*F12)+((D12-600)*E12))
Answer: You can write a nested IF statement as follows:
=IF(D12<=0,D12*L12,IF(D12>600,((600*F12)+((D12-600)*E12)),D12*F12))
Question:In Excel, I have this formula currently:
=IF(OR(A1>=40, B1>=40, C1>=40), "20", (A1+B1+C1)-20)
If one of my salesman does sale for $40-$49, then his commission is $20; however if his/her sale is less (for example $35) then the commission is that amount minus $20 ($35-$20=$15). I have 3 columns that are needed based on the type of sale. Only one column per row will be needed. The problem is that, when left blank, the total in the formula cell is -20. I need help setting up this formula so that when the 3 columns are left blank, the cell with the formula is left blank as well.
Answer: Using the AND function and the ISBLANK function, you can write your IF statement as follows:
=IF(AND(ISBLANK(A1),ISBLANK(B1),ISBLANK(C1)),"",IF(OR(A1>40, B1>40, C1>40), "20", (A1+B1+C1)-20))
In this formula, we are using the ISBLANK function to check if all 3 cells A1, B1, and C1 are blank, and if they are return a blank value («»). Then the rest is the formula that you originally wrote.
Question:In Excel, I need to create a simple booking and and out system, that shows a date out and a date back
«A1» = allows person to input date booked out
«A2» =allows person to input date booked back in
«A3″= shows status of product, eg, booked out, overdue return etc.
I can automate A3 with the following IF function:
=IF(ISBLANK(A2),"booked out","returned")
But what I cant get to work is if the product is out for 10 days or more, I would like the cell to say «send email»
Can you assist?
Answer: Using the TODAY function and adding an additional IF function, you can write your formula as follows:
=IF(ISBLANK(A2),IF(TODAY()-A1>10,"send email","booked out"),"returned")
Question:Using Microsoft Excel, I need a formula in cell U2 that does the following:
IF the date in E2<=12/31/2010, return T2*0.75
IF the date in E2>12/31/2010 but <=12/31/2011, return T2*0.5
IF the date in E2>12/31/2011, return T2*0
I tried using the following formula, but it gives me «#VALUE!»
=IF(E2<=DATE(2010,12,31),T2*0.75), IF(AND(E2>DATE(2010,12,31),E2<=DATE(2011,12,31)),T2*0.5,T2*0)
Can someone please help? Thanks.
Answer: You were very close…you just need to adjust your parentheses as follows:
=IF(E2<=DATE(2010,12,31),T2*0.75, IF(AND(E2>DATE(2010,12,31),E2<=DATE(2011,12,31)),T2*0.5,T2*0))
Question:In Excel, I would like to add 60 days if grade is ‘A’, 45 days if grade is ‘B’ and 30 days if grade is ‘C’. It would roughly look something like this, but I’m struggling with commas, brackets, etc.
(IF C5=A)=DATE(YEAR(B5)+0,MONTH(B5)+0,DAY(B5)+60),
(IF C5=B)=DATE(YEAR(B5)+0,MONTH(B5)+0,DAY(B5)+45),
(IF C5=C)=DATE(YEAR(B5)+0,MONTH(B5)+0,DAY(B5)+30)
Answer:You should be able to achieve your date calculations with the following formula:
=IF(C5="A",B5+60,IF(C5="B",B5+45,IF(C5="C",B5+30)))
Question:In Excel, I am trying to write a function and can’t seem to figure it out. Could you help?
IF D3 is < 31, then 1.51
IF D3 is between 31-90, then 3.40
IF D3 is between 91-120, then 4.60
IF D3 is > 121, then 5.44
Answer:You can write your formula as follows:
=IF(D3>121,5.44,IF(D3>=91,4.6,IF(D3>=31,3.4,1.51)))
Question:I would like ask a question regarding the IF statement. How would I write in Excel this problem?
I have to check if cell A1 is empty and if not, check if the value is less than equal to 5. Then multiply the amount entered in cell A1 by .60. The answer will be displayed on Cell A2.
Answer:You can write your formula in cell A2 using the IF function and ISBLANK function as follows:
=IF(AND(ISBLANK(A1)=FALSE,A1<=5),A1*0.6,"")
Question:In Excel, I’m trying to nest an OR command and I can’t find the proper way to write it. I want the spreadsheet to do the following:
If D6 equals «HOUSE» and C6 equals either «MOUSE» or «CAT», I want to return the value in cell B6. Otherwise, the formula should return the value «BLANK».
I tried the following:
=IF((D6="HOUSE")*(C6="MOUSE")*OR(C6="CAT"));B6;"BLANK")
If I only ask for HOUSE and MOUSE or HOUSE and CAT, it works, but as soon as I ask for MOUSE OR CAT, it doesn’t work.
Answer:You can write your formula using the AND function and OR function as follows:
=IF(AND(D6="HOUSE",OR(C6="MOUSE",C6="CAT")),B6,"BLANK")
This will return the value in B6 if D6 equals «HOUSE» and C6 equals either «MOUSE» or «CAT». If those conditions are not met, the formula will return the text value of «BLANK».
Question:In Microsoft Excel, I’m trying to write the following formula:
If cell A1 equals «jaipur», «udaipur» or «jodhpur», then cell A2 should display «rajasthan»
If cell A1 equals «bangalore», «mysore» or «belgum», then cell A2 should display «karnataka»
Please help.
Answer:You can write your formula using the OR function as follows:
=IF(OR(A1="jaipur",A1="udaipur",A1="jodhpur"),"rajasthan", IF(OR(A1="bangalore",A1="mysore",A1="belgum"),"karnataka"))
This will return «rajasthan» if A1 equals either «jaipur», «udaipur» or «jodhpur» and it will return «karnataka» if A1 equals either «bangalore», «mysore» or «belgum».
Question:In Microsoft Excel I’m trying to achieve the following with IF function:
If a value in any cell in column F is «food» then add the value of its corresponding cell in column G (eg a corresponding cell for F3 is G3). The IF function is performed in another cell altogether. I can do it for a single pair of cells but I don’t know how to do it for an entire column. Could you help?
At the moment, I’ve got this:
=IF(F3="food"; G3; 0)
Answer:This formula can be created using the SUMIF formula instead of using the IF function:
=SUMIF(F1:F10,"=food",G1:G10)
This will evaluate the first 10 rows of data in your spreadsheet. You may need to adjust the ranges accordingly.
I notice that you separate your parameters with semi-colons, so you might need to replace the commas in the formula above with semi-colons.
Question:I’m looking for an Exel formula that says:
If F3 is «H» and E3 is «H», return 1
If F3 is «A» and E3 is «A», return 2
If F3 is «d» and E3 is «d», return 3
Appreciate if you can help.
Answer:This Excel formula can be created using the AND formula in combination with the IF function:
=IF(AND(F3="H",E3="H"),1,IF(AND(F3="A",E3="A"),2,IF(AND(F3="d",E3="d"),3,"")))
We’ve defaulted the formula to return a blank if none of the conditions above are met.
Question:I am trying to get Excel to check different boxes and check if there is text/numbers listed in the cells and then spit out «Complete» if all 5 Boxes have text/Numbers or «Not Complete» if one or more is empty. This is what I have so far and it doesn’t work.
=IF(OR(ISBLANK(J2),ISBLANK(M2),ISBLANK(R2),ISBLANK (AA2),ISBLANK (AB2)),"Not Complete","")
Answer:First, you are correct in using the ISBLANK function, however, you have a space between ISBLANK and (AA2), as well as ISBLANK and (AB2). This might seem insignificant, but Excel can be very picky and will return a #NAME? error. So first you need to eliminate those spaces.
Next, you need to change the ELSE condition of your IF function to return «Complete».
You should be able to modify your formula as follows:
=IF(OR(ISBLANK(J2),ISBLANK(M2),ISBLANK(R2),ISBLANK(AA2),ISBLANK(AB2)), "Not Complete", "Complete")
Now if any of the cell J2, M2, R2, AA2, or AB2 are blank, the formula will return «Not Complete». If all 5 cells have a value, the formula will return «Complete».
Question:I’m very new to the Excel world, and I’m trying to figure out how to set up the proper formula for an If/then cell.
What I’m trying for is:
If B2’s value is 1 to 5, then multiply E2 by .77
If B2’s value is 6 to 10, then multiply E2 by .735
If B2’s value is 11 to 19, then multiply E2 by .7
If B2’s value is 20 to 29, then multiply E2 by .675
If B2’s value is 30 to 39, then multiply E2 by .65
I’ve tried a few different things thinking I was on the right track based on the IF, and AND function tutorials here, but I can’t seem to get it right.
Answer:To write your IF formula, you need to nest multiple IF functions together in combination with the AND function.
The following formula should work for what you are trying to do:
=IF(AND(B2>=1, B2<=5), E2*0.77, IF(AND(B2>=6, B2<=10), E2*0.735, IF(AND(B2>=11, B2<=19), E2*0.7, IF(AND(B2>=20, B2<=29), E2*0.675, IF(AND(B2>=30, B2<=39), E2*0.65,"")))))
As one final component of your formula, you need to decide what to do when none of the conditions are met. In this example, we have returned «» when the value in B2 does not meet any of the IF conditions above.
Question:Here is the Excel formula that has me between a rock and a hard place.
If E45 <= 50, return 44.55
If E45 > 50 and E45 < 100, return 42
If E45 >=200, return 39.6
Again thank you very much.
Answer:You should be able to write this Excel formula using a combination of the IF function and the AND function.
The following formula should work:
=IF(E45<=50, 44.55, IF(AND(E45>50, E45<100), 42, IF(E45>=200, 39.6, "")))
Please note that if none of the conditions are met, the Excel formula will return «» as the result.
Question:I have a nesting OR function problem:
My nonworking formula is:
=IF(C9=1,K9/J7,IF(C9=2,K9/J7,IF(C9=3,K9/L7,IF(C9=4,0,K9/N7))))
In Cell C9, I can have an input of 1, 2, 3, 4 or 0. The problem is on how to write the «or» condition when a «4 or 0» exists in Column C. If the «4 or 0» conditions exists in Column C I want Column K divided by Column N and the answer to be placed in Column M and associated row
Answer:You should be able to use the OR function within your IF function to test for C9=4 OR C9=0 as follows:
=IF(C9=1,K9/J7,IF(C9=2,K9/J7,IF(C9=3,K9/L7,IF(OR(C9=4,C9=0),K9/N7))))
This formula will return K9/N7 if cell C9 is either 4 or 0.
Question:In Excel, I am trying to create a formula that will show the following:
If column B = Ross and column C = 8 then in cell AB of that row I want it to show 2013, If column B = Block and column C = 9 then in cell AB of that row I want it to show 2012.
Answer:You can create your Excel formula using nested IF functions with the AND function.
=IF(AND(B1="Ross",C1=8),2013,IF(AND(B1="Block",C1=9),2012,""))
This formula will return 2013 as a numeric value if B1 is «Ross» and C1 is 8, or 2012 as a numeric value if B1 is «Block» and C1 is 9. Otherwise, it will return blank, as denoted by «».
Question:In Excel, I really have a problem looking for the right formula to express the following:
If B1=0, C1 is equal to A1/2
If B1=1, C1 is equal to A1/2 times 20%
If D1=1, C1 is equal to A1/2-5
I’ve been trying to look for any same expressions in your site. Please help me fix this.
Answer:In cell C1, you can use the following Excel formula with 3 nested IF functions:
=IF(B1=0,A1/2, IF(B1=1,(A1/2)*0.2, IF(D1=1,(A1/2)-5,"")))
Please note that if none of the conditions are met, the Excel formula will return «» as the result.
Question:In Excel, I need the answer for an IF THEN statement which compares column A and B and has an «OR condition» for column C. My problem is I want column D to return yes if A1 and B1 are >=3 or C1 is >=1.
Answer:You can create your Excel IF formula as follows:
=IF(OR(AND(A1>=3,B1>=3),C1>=1),"yes","")
Please note that if none of the conditions are met, the Excel formula will return «» as the result.
Question:In Excel, what have I done wrong with this formula?
=IF(OR(ISBLANK(C9),ISBLANK(B9)),"",IF(ISBLANK(C9),D9-TODAY(), "Reactivated"))
I want to make an event that if B9 and C9 is empty, the value would be empty. If only C9 is empty, then the output would be the remaining days left between the two dates, and if the two cells are not empty, the output should be the string ‘Reactivated’.
The problem with this code is that IF(ISBLANK(C9),D9-TODAY() is not working.
Answer:First of all, you might want to replace your OR function with the AND function, so that your Excel IF formula looks like this:
=IF(AND(ISBLANK(C9),ISBLANK(B9)),"",IF(ISBLANK(C9),D9-TODAY(),"Reactivated"))
Next, make sure that you don’t have any abnormal formatting in the cell that contains the results. To be safe, right click on the cell that contains the formula and choose Format Cells from the popup menu. When the Format Cells window appears, select the Number tab. Choose General as the format and click on the OK button.
Question:I was wondering if you could tell me what I am doing wrong.
Here are the instructions:
A customer is eligible for a discount if the customer’s 2016 sales greater than or equal to 100000 OR if the customers First Order was placed in 2016.
If the customer qualifies for a discount, return a value of Y
If the customer does not qualify for a discount, return a value of N.
Here is the formula I’ve entered:
=IF(OR([2014 Sales]=0,[2015 Sales]=0,[2016 Sales]>=100000),"Y","N")
I only have 2 cells wrong. Can you help me please? I am very lost and confused.
Answer:You are very close with your IF formula, however, it looks like you need to add the AND function to your formula as follows:
=IF(OR([2016 Sales]>=100000,AND([2014 Sales]=0,[2015 Sales]=0),C8>=100000),"Y","N")
This formula should return Y if 2016 sales are greater than or equal to 100000, or if both 2014 sales and 2015 sales are 0. Otherwise, the formula will return N. You will also notice that we switched the order of your conditions in the formula so that it is easier to understand the formula based on your instructions above.
Question:Could you please help me? I need to use «OR» on my formula but I can’t get it to work. This is what I’ve tried:
=IF(C6>=0<=150,150000,IF(C6>=151<=160,158400))
Here is what I need the formula to do:
IF C6 IS >=0 OR <=150 THEN ASSIGN $150000
IF C6 IS >=151 OR <=160 THEN ASSIGN $158400
Answer:You should be able to use the AND function within your IF function as follows:
=IF(AND(ISBLANK(C6)=FALSE,C6>=0,C6<=150),150000,IF(AND(C6>=151,C6<=160),158400,""))
Notice that we first use the ISBLANK function to test C6 to make sure that it is not blank. This is because if C6 if blank, it will evalulate to greater than 0 and thus return 150000. To avoid this, we include ISBLANK(C6)=FALSE as one of the conditions in addition to C6>=0 and C6<=150. That way, you won’t return any false results if C6 is blank.
Question:I am having a problem with a formula, I want it to be IF E5=N then do the first formula, else do the second formula. Excel recognizes the =IF(logical_test,value_if_TRUE,value_if_FALSE)
but doesn’t like the formula below:
=IF(e5="N",((AND(AH5-AG5<456, AH5-S5<822)), "Compliant", "not Compliant"),((AH5-S5<822), "Compliant", "not Compliant"))
Any help would be greatly appreciated.
Answer:To have the first formula executed when E5=N and then second formula executed when E5<>N, you will need to nest 2 additional IF functions within the main IF function as follows:
=IF(E5="N", IF((AND(AH5-AG5<456, AH5-S5<822)), "Compliant", "not Compliant"), IF((AH5-S5<822), "Compliant", "not Compliant"))
If E5=»N», the first nested IF function will be executed:
IF((AND(AH5-AG5<456, AH5-S5<822)), "Compliant", "not Compliant")
Otherwise,the second nested IF function will be executed:
IF((AH5-S5<822), "Compliant", "not Compliant"))
Question:I need to write a formula based on the following logic:
There is a maximum discount allowed of £1000 if the capital sum is less that £43000 and a lower discount of £500 if the capital sum is above £43000. So the formula should return either £500 or £1000 in the cell but the £43000 is made up of two numbers, say for e.g. £42750+350 and if the second number is less than the allowed discount, the actual lower value is returned — in this case the £500 or £1000 becomes £350. Or as another e.g. £42000+750 returns £750.
So on my spreadsheet, in this second e.g. I would have A1= £42000, A2=750, A3=A1+A2, A4=the formula with the changing discount, in this case £750.
How can I write this formula?
Answer:In cell A4, you can calculate the correct discount using the IF function and the MIN function as follows:
=IF(A3<43000, MIN(A2,1000), MIN(A2,500))
If A3 is less than 43000, the formula will return the lower value of A2 and 1000. Otherwise, it will return the lower value of A2 and 500.
Question: I have a list of sizes in column A with sizes 100, 200, 300, 400, 500, 600. Then I have another column B, with sizes of my products, and it is random, for example, 318, 445, 527. What I’m trying to create is for a value of 318 in column B, I need to return 400 for that product. If the value in column B is 445, then I should return 500 and so on, as long sizes in column A must be BIGGER to the NEAREST size to column B.
Any idea how to create this function?
Answer:If your sizes are in increments of 100, you can create this function by taking the value in column B, dividing by 100, rounding up to the nearest integer, and then multiplying by 100.
For example in cell C2, you can use the IF function and the ROUNDUP function as follows:
=ROUNDUP(B2/100,0)*100
This will return the correct value of 400 for a value of 318 in cell B2. Just copy this formula to cell C3, C4 and so on.
The syntax of the IF() function is the following:
= IF ( logical_test , [value_if_TRUE] , [value_if_FALSE] )
The first two attributes are obligatory, i.e. without them, the formula doesn’t work, and produces an error message.
- logical _test – a placeholder for the condition we want to test
- value_if_TRUE – an attribute where we need to specify a value (text, or another function) that the IF formula returns when the result of the logical_test is TRUE
The third parameter is Optional, i.e. we can skip it and in such a case, the IF() function returns the default value FALSE.
- value_if_FALSE – an attribute for a value, text or another formula that the IF() function must return when the result of the logical test is FALSE.
In other words, IF() function is used to test the specific conditions and can be described as the statement:
IF something is true, THEN return the first value, ELSE – return then second value.
The simplest IF() function may be written with the first two parameters only.
For example, this formula is absolutely correct:
=IF(C2=1,"Hello!")
This formula tests the condition we set (C2=1) and if it is true, the formula returns the text message (“Hello!”).
Otherwise, it returns the default value FALSE.
Interesting Fact!!! You can use another simpler test in Excel for a certain condition. Just place a formula like “=C2>C3” in a cell and press ENTER. If this statement is true, the formula returns the default value – TRUE. Else (i.e. when a value in C2 is NOT larger than a value in C3 cell) the formula will return another default value – FALSE. We use the IF() function in these cases; when we want to trigger some further actions or calculations depending on the results of the logical test.
Typically, the IF() function is used in situations when we need to calculate or flag the results based on certain conditions (for example, smaller than, equal to, greater than and others).
Despite the fact that Excel usually provides multiple choices on how to solve every specific task, the IF() function can play a good role in such cases.
Another simple example of the IF() function:
=IF(C3="Hello!",1, 0)
If a value of the C3 cell is the text “Hello!” then this formula returns the one (1) value.
Else (i.e. if this cell contains any other text, number or blank value), the formula returns zero.
The big advantage of the IF() function (like many other Excel functions) is how we can replace all three arguments in this example with whatever we want/need and it still works properly (if we follow the syntax, of course).
For example, let’s replace the one (as a value_if_true) to another formula “C3+C4” and replace zero value (0) to TODAY() function.
Our initial formula becomes:
=IF(C3="Hello!",C2+C3,TODAY())
That means – IF a value in C2 cell equals one, THEN do the addition C2+C3.
ELSE (i.e. when C2 doesn’t equal “Hello!”), THEN execute the TODAY() function and return its result.
IF() function is a universal function, i.e. it accepts as an attribute different types of a value, such as numeric value, text, date/time, other functions, named ranges and others).
The IF function can be easily used as a part of other more complex formulas.
Moreover, you can use the so-called nested IF() function and replace the [value_if_false] with another IF() function.
The most common reason to do that is when you need to create a multi-choice comparison like a waterfall.
The last value_if_FALSE attribute is a value that we want the formula to return if the result of ALL logical tests in the formula is FALSE.
We know that we need to use a nested IF() (i.e. one IF() inside another IF() statement) when we have a “but” keyword inside the sentence with a logical test.
Take a look at the screenshot below.
In this example, we need to add the text “flag” if a value is greater than 200, BUT if this value is less than 50 we need to return “follow up” text.
We know that we need to use a nested IF() when there is the “but” keyword in the logical test.
Pro Tip: Be cautious. The more IF iterations we use, the more complex the formula becomes and the more difficult it is to understand. In addition, the complex formulas that contain multiple IF functions along with other Excel functions may slow down the calculation speed, especially if they use large ranges of cells. Also, it’s very easy to make an accidental mistake or typo inside the long and complex formulas, and such errors are difficult to trace properly.
The IF() function is often used with other logical functions such as AND() or OR() functions that we will discuss further.
Let’s look at some practical examples…
TEST CASE №1 Adding the word “Good” if the Revenue is greater than 15000
This is a typical use of the IF() function.
Let’s flag all apps if their Revenue is above 15,000.
Step 1. Go to the first cell where we need to insert a formula (cell C5 in this example).
Start the formula with an equal sign (=), add the keyword IF and the opened parentheses to make the formula look like:
=IF(
Step 2. The first argument of the IF() function is a logical test.
In this example, we want to flag a value in cell B5 (Revenue) if it is above 15000.
So, let’s continue the formula =IF(B5>15000,
Do not forget to put a comma once this step is ready.
This coma is used by Excel as a delimiter to separate the arguments from each other.
Pro tip: We can either type a numeric value in the logical test or use a cell reference to a cell that contains such a value (C2 cell in our example). The second approach is preferred because it gives us more flexibility in the future. Once we copy/paste the formula to the entire range, all we need to do in this case – if want to change that value – is go to the referral cell and change it there without needing to re-write the formula for all related cells.
NOTE: Keep in mind that if we want to use this approach, we need to fix the cell reference to look like $C$2. This fixed cell address is required for copying the formula to the entire range. Without that, the formula will return the wrong result. We can simply press F4 to fix the cell reference in the formula (make sure that the cursor is located near the appropriate cell address)
The formula becomes:
=IF(B5>$C$2,
Step 3. The second argument of IF() function, as we remember, is a value_if_TRUE.
Let’s type the text “Good” as a second attribute in the formula:
=IF(B5>$C$2, "Good",
Do not forget to put a comma once this step is ready.
Also, be careful – if you type a text value, you need to put it inside a double quotation mark (“your text”)
Pro tip: We can either type a numeric value in the logical test or use a cell reference to a cell that contains such a value (C3 cell in our example). If in the future we’ll decide to change the “Good” word to something else (“Not Bad”, for example), then all we need to do is go to cell C3 and change that text in the cell without the necessity to re-do the entire formula.
Our formula becomes:
=IF(B5>$C$2,$C$3,
NOTE: Don’t forget to fix the cell reference to look like $C$3 address. Press F4 to make an absolute reference. Without that, the formula will return a wrong result.
Step 4. The third argument of the IF() function is value_if_FALSE. We can skip this attribute (in such cases Excel returns the default value – FALSE). However, if we want to do that in a more aesthetic way, let the formula return a blank value. The blank value in Excel is equal to nothing between two quotation marks, like “”. So, the final version of the formula becomes:
=IF(B5>$C$2,$C$3,"")
NOTE: Don’t forget to close the brackets and press ENTER.
Step 5. Drag the formula down to the entire range.
Make a quick check manually to ensure that the formula returns the correct result according to our expectations.
TEST CASE №2 Adding the word “Good” if the Revenue is greater than 15000 and less than 20000
Let’s flag all apps if their Revenue is above 15,000 but under 20,000
Step 1. Go to the first cell where we need to insert a formula (cell D5 in this example).
Start the formula with an equal sign (=), add the keyword IF and the opened parentheses to make the formula look like:
=IF(
Step 2. The first argument of the IF() function is a logical test.
In this example, we want to flag a value in cell B5 (Revenue) if it is above 15000 and less than 20,000.
This is a typical situation when we can use the AND() logical function to unite several certain conditions into a single logical test.
AND() function can accept up to 255 conditions as its arguments.
Let’s continue the formula and add the second keyword AND with an opened parenthesis.
Once we’ve done that, we can type both conditions for the logical test inside AND() block and close its second parenthesis.
The formula looks like:
=IF(AND(B5>$D$2,B5<$D$3),
NOTE: Don’t forget to fix the cell reference to look like $D$2 and $D$3 address.
Press F4 to make an absolute reference.
Without that, the formula will return a wrong result after we drag it down to the entire range.
NOTE: Don’t forget to use a comma once this step is ready.
This comma is used by Excel as a delimiter to separate the arguments from each other.
Step 2. The second argument of IF() function, as we remember, is a value_if_TRUE.
Let’s add another cell reference as a second attribute in the formula:
=IF(AND(B5>$D$2,B5<$D$3),$C$3,
NOTE: Don’t forget to put a comma after the attribute once this step is ready. Be careful. If you type a text value, you need to put it inside a double quotation mark (“your text”)
Step 3. The third argument of the IF() function is a value_if_FALSE.
We can skip this attribute and Excel returns the default value – FALSE.
However, the more aesthetic way to do that is to return nothing (or blank value).
Nothing in Excel is denoted as a double quotation mark without any space:
=IF(AND(B5>$D$2,B5<$D$3),$C$3,"")
NOTE: Don’t forget to close the bracket and press ENTER.
Step 4. Drag the formula down to the entire range.
Make a quick check manually to ensure that the formula returns the correct result according to our expectations.
TEST CASE №3 Adding the word “Good” if the Revenue is greater than 15000 and less than 20000. Adding the word “Exceptional” if the Revenue is greater than or equal to 20,000. Otherwise, keeping the values
This time we’ll flag all apps as “Good” if their Revenue is above 15,000 and under 20,000.
In addition, we’ll flag them as “Exceptional” if their Revenue is greater than or equal to 20,000
Step 1. Go to the first cell where we need to insert a formula (cell E5 in this example).
Start the formula with an equal sign (=), add the keyword IF and the open parentheses to make the formula look like:
=IF(
Step 2. The first argument of the IF() function is a logical test.
The first part of the formula in this example is the same as we wrote in the previous example:
=IF(AND(B5>$E$2,B5<$E$3),$C$3,
NOTE: Don’t forget to to put a comma after the attribute once this step is ready.
Step 3. Usually, the third argument of the IF() function is a value_if_FALSE.
However, this time we need to add the second condition when a value in cell B5 is greater than or equal to 20,000.
We can do that if we use nested IF() function.
Let’s add another IF() block as a third parameter now:
=IF(AND(B5>$E$2,B5<$E$3),$C$3,IF(
Step 4. Add the second logical test, and the second value_if_TRUE.
In our example, the formula must return the “Exceptional” keyword if the value in cell B5 is greater than or equal to 20,000.
Let’s type this:
=IF(AND(B5>$E$2,B5<$E$3),$C$3,IF(B5>=$E$3,"Exceptional",
NOTE: If you type a value as a text, you need to put it inside a double quotation mark (“your text”)
Step 5. We need to write a value that the formula will return if the result of both logical tests is FALSE.
In our example, the formula must return the raw Revenue value in this case.
Let’s place this attribute as the third argument in the second IF() block:
=IF(AND(B5>$E$2,B5<$E$3),$C$3,IF(B5>=$E$3,"Exceptional",B5))
NOTE: Don’t forget to close the brackets.
We created two IF blocks, so we need to close two brackets at the end.
Step 6. Drag the formula down to the entire range.
Make a quick check manually to ensure that the formula returns the correct result according to our expectations.
TEST CASE №4 Adding the word “Flag” if the Revenue is greater than or equal to 20,000 OR it is lesser than or equal to 15,000
Let’s flag all apps if their Revenue is <= 15,000 or >= 20,000
Step 1. Go to the first cell where we need to insert a formula (cell D5 in this example).
Start the formula with an equal sign (=), add the keyword IF and the open parentheses to make the formula look like:
=IF(
Step 2. The first argument of the IF() function is a logical test.
In this example we want to flag a value in cell B5 (Revenue) if it is below or equal to 15000 OR above or equal to 20,000.
This is a situation when we can use OR() logical function that allows the testing of multiple logical conditions and return a true value if ANY of them is true.
Let’s continue the formula and add the second keyword OR with an opened bracket.
Once we’ve done that, we can type both conditions for the logical test inside OR() block and close its second parentheses.
The formula looks like:
=IF(OR(B5>=$F$2,B5=<$F$3),
NOTE: Press the F4 button on the keyboard to make an absolute reference.
Step 3. The second argument of the IF() function, as we remember, is a value_if_TRUE.
Let’s add this attribute in the formula:
=IF(AND(B5>$D$2,B5<$D$3),"Flag",
NOTE: If you type a text value, you need to put it inside a double quotation mark (“your text”)
Step 4. The third argument of the IF() function is a value_if_FALSE.
Let’s add a double quotation mark without any space to return a blank value:
=IF(AND(B5>$D$2, B5<$D$3),"Flag","")
NOTE: Don’t forget to close the bracket and press ENTER.
Step 5. Drag the formula down to the entire range.
Quickly check to ensure that the formula returns the correct result.
TEST CASE №5 Using other formulas inside the logical functions
Let’s calculate the difference between Actual Revenue and Budget Revenue and flag those cases when the difference is larger than +/- 10%.
Step 1. The easiest way to start building such a complex formula is to calculate the core value (this is the +/-10% threshold value in our case).
Step 2. Go to the first cell where we need to insert a formula (cell D23 in this example).
Start the formula with an equal sign (=), add the formula to calculate the difference (Actual divided by Budget minus one:
=B23/C23 - 1
Step 3. Let’s add the IF() block and the appropriate logical test.
This is a situation when we can use the OR() logical function as we need to flag a value if it is greater than +10% or lower than -10%:
=IF(OR(B23/C23 - 1>10%,B23/C23 - 1<-10%),
Step 4. The second argument of the IF() function, as we remember, is a value_if_TRUE.
In this example we need to return the exact deviation, so let’s do that, by simply copying the initial formula.
=IF(OR(B23/C23 - 1>10%,B23/C23 - 1<-10%),B23/C23 - 1,
Step 5. The third argument of the IF() function is a value_if_FALSE.
Let’s add a double quotation mark without any space to return a blank value:
=IF(OR(B23/C23 - 1>10%,B23/C23 - 1<-10%),B23/C23 - 1,"")
NOTE: Don’t forget to close the bracket and press ENTER.
Step 6. Drag the formula down to the entire range.
Quickly check to ensure that the formula returns the correct result.
TEST CASE №6 Using text symbols as the result of the IF() function
Let’s mark the positive deviation with the up arrow and the negative deviation with the down arrow.
Step 1. We’ll continue the previous example.
Let’s say we want to mark all positive deviations with a symbol that looks like an up arrow and all negative deviations with a symbol that looks like a down arrow.
First of all, a few preparations.
Let’s go to the cells above the test range (A20 and A21 cells in this example).
Feel free to select any other cells if you prefer.
Step 2. Insert the symbols that will indicate all positive and negative deviations.
To do this, we need to go on the INSERT tab on the Excel Ribbon and follow the path: INSERT > Symbol > Arial > Geometric Shapes
Click Insert once you have selected a shape.
Go to another cell below and insert the second arrow in the same way.
Step 3. Go to the first cell in the range where we want to add these visual indicators.
Replicate the IF() function with the cell references containing the arrows as the value_if_TRUE and value_if_FALSE attributes.
=IF(B23/C23 - 1>10%,$A$20,IF(B23/C23 - 1<-10%,$A$21,""))
NOTE: Don’t forget to close the bracket and press ENTER.
Step 4. Drag the formula down to the entire range.
Quickly check that the formula returns the correct result.
Workbook for Download
Feel free to Download the Workbook HERE.
Published on: February 1, 2018
Last modified: February 24, 2023
Leila Gharani
I’m a 5x Microsoft MVP with over 15 years of experience implementing and professionals on Management Information Systems of different sizes and nature.
My background is Masters in Economics, Economist, Consultant, Oracle HFM Accounting Systems Expert, SAP BW Project Manager. My passion is teaching, experimenting and sharing. I am also addicted to learning and enjoy taking online courses on a variety of topics.
The IF function runs a logical test and returns one value for a TRUE result, and another value for a FALSE result. The result from IF can be a value, a cell reference, or even another formula. By combining the IF function with other logical functions like AND and OR, you can test more than one condition at a time.
Syntax
The generic syntax for the IF function looks like this:
=IF(logical_test,[value_if_true],[value_if_false])
The first argument, logical_test, is typically an expression that returns either TRUE or FALSE. The second argument, value_if_true, is the value to return when logical_test is TRUE. The last argument, value_if_false, is the value to return when logical_test is FALSE. Both value_if_true and value_if_false are optional, but you must provide one or the other. For example, if cell A1 contains 80, then:
=IF(A1>75,TRUE) // returns TRUE
=IF(A1>75,"OK") // returns "OK"
=IF(A1>85,"OK") // returns FALSE
=IF(A1>75,10,0) // returns 10
=IF(A1>85,10,0) // returns 0
=IF(A1>75,"Yes","No") // returns "Yes"
=IF(A1>85,"Yes","No") // returns "No"
Notice that text values like «OK», «Yes», «No», etc. must be enclosed in double quotes («»). However, numeric values should not be enclosed in quotes.
Logical tests
The IF function supports logical operators (>,<,<>,=) when creating logical tests. Most commonly, the logical_test in IF is a complete logical expression that will evaluate to TRUE or FALSE. The table below shows some common examples:
Goal | Logical test |
---|---|
If A1 is greater than 75 | A1>75 |
If A1 equals 100 | A1=100 |
If A1 is less than or equal to 100 | A1<=100 |
If A1 equals «Red» | A1=»red» |
If A1 is not equal to «Red» | A1<>»red» |
If A1 is less than B1 | A1<B1 |
If A1 is empty | A1=»» |
If A1 is not empty | A1<>»» |
If A1 is less than current date | A1<TODAY() |
Notice text values must be enclosed in double quotes («»), but numbers do not. The IF function does not support wildcards, but you can combine IF with COUNTIF to get basic wildcard functionality. To test for substrings in a cell, you can use the IF function with the SEARCH function.
Pass or Fail example
In the worksheet shown above, we want to assign either «Pass» or «Fail» based on a test score. A passing score is 70 or higher. The formula in D6, copied down, is:
=IF(C5>=70,"Pass","Fail")
Translation: If the value in C5 is greater than or equal to 70, return «Pass». Otherwise, return «Fail».
Note that the logical flow of this formula can be reversed. This formula returns the same result:
=IF(C5<70,"Fail","Pass")
Translation: If the value in C5 is less than 70, return «Fail». Otherwise, return «Pass».
Both formulas above, when copied down, will return correct results.
Note: If you are new to the idea of formula criteria, this article explains many examples.
Assign points based on color
In the worksheet below, we want to assign points based on the color in column B. If the color is «red», the result should be 100. If the color is «blue», the result should be 125. This requires that we use a formula based on two IF functions, one nested inside the other. The formula in C5, copied down, is:
=IF(B5="red",100,IF(B5="blue",125))
Translation: IF the value in B5 is «red», return 100. Else, if the value in B5 is «blue», return 125.
There are three things to notice in this example:
- The formula will return FALSE if the value in B5 is anything except «red» or «blue»
- The text values «red» and «blue» must be enclosed in double quotes («»)
- The IF function is not case-sensitive and will match «red», «Red», «RED», or «rEd».
This is a simple example of a nested IFs formula. See below for a more complex example.
Return another formula
The IF function can return another formula as a result. For example, the formula below will return A1*5% when A1 is less than 100, and A1*7% when A1 is greater than or equal to 100:
=IF(A1<100,A1*5%,A1*7%)
Nested IF statements
The IF function can be «nested». A «nested IF» refers to a formula where at least one IF function is nested inside another in order to test for more conditions and return more possible results. Each IF statement needs to be carefully «nested» inside another so that the logic is correct. For example, the following formula can be used to assign a grade rather than a pass / fail result:
=IF(C6<70,"F",IF(C6<75,"D",IF(C6<85,"C",IF(C6<95,"B","A"))))
Up to 64 IF functions can be nested. However, in general, you should consider other functions, like VLOOKUP or XLOOKUP for more complex scenarios, because they can handle more conditions in a more streamlined fashion. For a more details see this article on nested IFs.
Note: the newer IFS function is designed to handle multiple conditions without nesting. However, a lookup function like VLOOKUP or XLOOKUP is usually a better approach unless the logic for each condition is custom.
IF with AND, OR, NOT
The IF function can be combined with the AND function and the OR function. For example, to return «OK» when A1 is between 7 and 10, you can use a formula like this:
=IF(AND(A1>7,A1<10),"OK","")
Translation: if A1 is greater than 7 and less than 10, return «OK». Otherwise, return nothing («»).
To return B1+10 when A1 is «red» or «blue» you can use the OR function like this:
=IF(OR(A1="red",A1="blue"),B1+10,B1)
Translation: if A1 is red or blue, return B1+10, otherwise return B1.
=IF(NOT(A1="red"),B1+10,B1)
Translation: if A1 is NOT red, return B1+10, otherwise return B1.
IF cell contains specific text
Because the IF function does not support wildcards, it is not obvious how to configure IF to check for a specific substring in a cell. A common approach is to combine the ISNUMBER function and the SEARCH function to create a logical test like this:
=ISNUMBER(SEARCH(substring,A1)) // returns TRUE or FALSE
For example, to check for the substring «xyz» in cell A1, you can use a formula like this:
=IF(ISNUMBER(SEARCH("xyz",A1)),"Yes","No")
Read a detailed explanation here.
More information
- Read more about nested IFs
- Learn how to use VLOOKUP instead of nested IFs (video)
- 50 Examples of formula criteria
Notes
- The IF function is not case-sensitive.
- To count values conditionally, use the COUNTIF or the COUNTIFS functions.
- To sum values conditionally, use the SUMIF or the SUMIFS functions.
- If any of the arguments to IF are supplied as arrays, the IF function will evaluate every element of the array.
Complex Formulas in Excel (Table of Contents)
- Introduction to Complex Formulas in Excel
- Choose Function Serve as Lookup Function
- VLOOKUP With CHOOSE
- IF With AND & OR Function
Introduction to Complex Formulas in Excel
Excel comes with many useful formulas; we have a category of Financial, Logical, Text, Date & Time, Lookup & References, and Math & Trig”. Each individual formulas are good enough for intermediate users where they face straight forward situations, but as you progress to the next level, your skill needs to take the elevation, so in that regard, applying more complex formulas in excel plays a vital role in solving complex situations. Keeping this in mind, this article, we will take you through some of the important and much-needed complex formulas. Read on.
Choose Function Serve as Lookup Function
Not many of you have used CHOOSE function, but this is very useful to serve as the lookup function as well.
You can download this Complex Formulas Excel Template here – Complex Formulas Excel Template
For example, look at the below data.
We have data of customers on a monthly basis under this table; we have each customer table. In this table, in cell B13, I have created the drop-down list of the month so that when this drop-down changes, we should get the total of the selected month.
Create one table like the one below.
Apply VLOOKUP to cell D13.
Now open CHOOSE function in cell B14.
Select the INDEX Number as a VLOOKUP cell and make it an absolute reference.
Now select for each argument each month sales numbers.
Close the bracket and hit the enter key.
Now copy and paste the formula to the below cells as well.
Now CHOOSE formula will show the numbers of the selected month.
VLOOKUP With CHOOSE Function
We have seen tradition VLOOKUP, but we can combine it with CHOOSE function as well. For example, look at the below data.
In cells A1 to B11, we have a sales table, and in cell D2, I have created the drop-down list of months, and in cell E2, we need to apply VLOOKUP and get the selected month sales value. But the problem to apply VLOOKUP is a data structure, where the lookup value is to the right of the result column, so VLOOKUP cannot fetch the data from right to left; in this case, we can use CHOOSE function.
In order to select the table array, we need to open the CHOOSE function here.
In the INDEX Number argument in flower, brackets enter 1 & 2. Now select the first range as the Month column.
Select the Sales column as the second range.
Mention column index number as 2 and range lookup as 0.
So we got the result for the month of Apr from the table. So, whenever you don’t have an accurate data structure, we can select, CHOOSE function.
IF With AND & OR Function
Logical functions are full of logic to calculate the stuff. Take a look at the below example data.
From the above table, we need to calculate the bonus based on the below conditions.
- If the Service is more than 1.5 years and if the department is either Sales or Support, then Bonus is 1000.
- If anything else, then Bonus is 3000.
To calculate the bonus, we need to apply IF, AND, & OR together. Open IF condition in cell D2.
We need to test multiple conditions, open AND function.
Now the next logical is either Sale or Support so, for this open OR condition.
Test whether the title is Sales or Support.
So, if all the supplied conditions are TRUE, then the bonus should be 10000.
If the supplied logical tests are FALSE, then the bonus is 3000.
Close the bracket and hit Enter key; we should get the result.
Copy and paste the formula to the below cells.
So, according to the condition, we got the result. If the service is >1.5 years and the title is either Sales or Support, we will get 10000 or else we will get 3000.
Complex Formula with Wildcard Characters
VLOOKUP requires an exact lookup value to be matched to fetch the data. This is the traditional slogan, but we can still fetch the data by using the particle lookup value. For example, if the lookup value is “VIVO” and in the main table, we can still match using wildcard characters if it is “VIVO Mobile”. We will see one of the examples now; below is the example data.
We have Lookup Table in column A. In column C, we have lookup values; these lookup values are not exactly the same as the lookup table values. So we will see how to apply VLOOKUP using wild cards.
First, open the VLOOKUP function in cell D1.
The first argument is the Lookup Value. One of the problems with the lookup value here is we don’t have an exact match, so we need to enclose this lookup value with an asterisk before and after the lookup value.
Here we have applied two asterisk characters, “*”&C2&”*”. Here asterisk indicates anything in between the wildcard should be matched and return the related result.
Even though we had just “Infosys”, the asterisk character matched the value in the lookup table and returned the exact result as “Infosys Ltd”.
Similarly, in cell D6, we got an error value as #VALUE! Because there is no word “Mintra” in the lookup table.
Recommended Articles
This is a guide to Complex Formulas in Excel. Here we discuss some of the important and much-needed complex formulas with examples and excel template. You can also go through our other suggested articles to learn more –
- SEARCH Formula in Excel
- Advanced Formulas in Excel
- TRIM Formula in Excel
- Text Formula In Excel
What is the IF function?
The IF function is an Excel function that is used to test for a logical condition and return different values depending upon it.
For example you could test if cell A1 contains the number 1 and return “Yes” if it does using this formula:
=IF(A1=1,”Yes,”No”)
If you’re unfamiliar with Excel formulas and functions you could greatly benefit from our free Basic Skills E-book.
Advanced functions such as IF are covered in depth in our Expert Skills Books and E-books.
The problem with nested IF functions
Sometimes you need to test for more than one condition at the same time. Consider this example:
In this example you want to use an IF function to determine whether employees are paid a bonus or not. Only employees who have exceeded their quota and are paid a quota bonus should receive a bonus.
You could solve this problem using ‘nested’ IF functions. Nesting means placing one function inside another function. The formula would look like this:
=IF(B2>C2,IF(D2=”Yes”,”Paid Bonus!”,”No Bonus”),”No Bonus”)
If this formula doesn’t already look complicated to you, imagine how it would look with 3 nested IF functions or even more!
Nesting functions isn’t necessarily incorrect, but it tends to make formulas harder to understand and more prone to error.
Simplifying the formula with the AND function
Excel’s AND function allows you to test for multiple conditions within a single function. Here’s how the formula looks using the AND function instead of two nested IF functions.
=IF(AND(B2>C2,D2=”Yes”),”Paid Bonus!”,”No Bonus”)
This has greatly simplified the formula, and is the correct approach if you need to return a single result in response to multiple conditions. Excel also contains an OR function that returns a result if any one of the conditions within it are true.
AND and OR are explained in much greater depth in our Expert Skills Books and E-books.
Sample workbook
You can download a sample workbook showing both formulas in action.
An alternative solution using helper columns
There are some cases where multiple IF functions are needed. This can result in some very complex formulas.
You can help to simplify complex formulas by dividing them into multiple smaller formulas in different columns, known as ‘helper columns’. If you don’t want these to be visible to users you can always hide the helper columns.
These are the only up-to-date Excel books currently published and includes the new Dynamic Arrays features.
They are also the only books that will teach you absolutely every Excel skill including Power Pivot, OLAP and DAX.
Some of the things you will learn