IF function
The IF function is one of the most popular functions in Excel, and it allows you to make logical comparisons between a value and what you expect.
So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.
For example, =IF(C2=”Yes”,1,2) says IF(C2 = Yes, then return a 1, otherwise return a 2).
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])
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. |
Simple IF examples
-
=IF(C2=”Yes”,1,2)
In the above example, cell D2 says: IF(C2 = Yes, then return a 1, otherwise return a 2)
-
=IF(C2=1,”Yes”,”No”)
In this example, the formula in cell D2 says: IF(C2 = 1, then return Yes, otherwise return No)As you see, the IF function can be used to evaluate both text and values. It can also be used to evaluate errors. You are not limited to only checking if one thing is equal to another and returning a single result, you can also use mathematical operators and perform additional calculations depending on your criteria. You can also nest multiple IF functions together in order to perform multiple comparisons.
-
=IF(C2>B2,”Over Budget”,”Within Budget”)
In the above example, the IF function in D2 is saying IF(C2 Is Greater Than B2, then return “Over Budget”, otherwise return “Within Budget”)
-
=IF(C2>B2,C2-B2,0)
In the above illustration, instead of returning a text result, we are going to return a mathematical calculation. So the formula in E2 is saying IF(Actual is Greater than Budgeted, then Subtract the Budgeted amount from the Actual amount, otherwise return nothing).
-
=IF(E7=”Yes”,F5*0.0825,0)
In this example, the formula in F7 is saying IF(E7 = “Yes”, then calculate the Total Amount in F5 * 8.25%, otherwise no Sales Tax is due so return 0)
Note: If you are going to use text in formulas, you need to wrap the text in quotes (e.g. “Text”). The only exception to that is using TRUE or FALSE, which Excel automatically understands.
Common problems
Problem |
What went wrong |
---|---|
0 (zero) in cell |
There was no argument for either value_if_true or value_if_False arguments. To see the right value returned, add argument text to the two arguments, or add TRUE or FALSE to the argument. |
#NAME? in cell |
This usually means that the formula is misspelled. |
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
See Also
IF function — nested formulas and avoiding pitfalls
IFS function
Using IF with AND, OR and NOT functions
COUNTIF function
How to avoid broken formulas
Overview of formulas in Excel
Need more help?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.
This is a step-by-step guide on how to use IF function in Excel. It shows you how to create a formula using the IF function, it includes several IF formula examples, an introduction on how to use nested IF formulas, and the exercise file I used when creating this tutorial.
The Excel IF function performs a logical test and returns one value when the condition is TRUE and another when the condition is FALSE.
How do you write an if-then formula in Excel? Well, the syntax for IF statements is the same in all Excel versions. This means that you can use any of the examples shown in this article in Excel for Microsoft 365 or Excel 2021, 2019, 2016, 2013, 2010, 2007, and 2003.
How to use IF function in Excel:
- Select the cell where you want to insert the IF formula. Using your mouse or keyboard, navigate to the cell where you want to insert your formula.
- Type =IF(
- Insert the condition that you want to check, followed by a comma (,). The first argument of the IF function is the logical_test. This is the condition that you want to validate. For example C6 > 70.
- Insert the value to display when the condition is TRUE, followed by a comma (,). The second argument of the IF function is value_if_true. Here, you can insert a nested formula or a simple message such as “YES”.
- Insert the value to display when the condition is FALSE. The last argument of the IF function is value_if_false. Just like the previous step, you can insert a nested formula or display a message such as “NO”. This can also be set as an empty string (“”), which will display a cell that looks blank.
- Type ) to close the function and press ENTER
The following video shows you exactly how to apply the six steps described above and create your first IF formula.
The syntax that shows how to create an IF function in Excel is explained below:=IF(logical_test, [value_if_true], [value_if_false])
IF is a logical function and implies setting 3 arguments:
logical_test – The logical condition that you want to test. This will return either a TRUE or a FALSE value.
value_if_true – [optional] The value or formula which will be used when logical_test is TRUE.
value_if_false – [optional] The value or formula which will be used when logical_test is FALSE.
Please remember that while both value_if_true and value_if_false are optional, at least one of them needs to be supplied. Otherwise, your IF formula will simply return 0 (zero).
Where is the IF function in Excel? Since this is a logical function, you can find the IF function in the Formulas tab, Function Library section, under Logical.
Logical operators for IF function
The IF function is one of the most used Excel functions, and it allows you to return different values when the logical condition supplied is TRUE or FALSE. An Excel if-then formula can use the following logical operators:
Logical operators | Definition | Example |
= | equal to | A1=B1 |
<> | not equal to | A1<>B1 |
> | greater than | A1>B1 |
>= | greater than or equal to | A1>=B1 |
< | lower than | A1<B1 |
<= | lower than or equal to | A1<=B1 |
The IF function doesn’t support wildcards.
Your first IF formula
The IF function runs a logical test and returns different values depending on whether the result is TRUE or FALSE. The result from IF can be a value, a cell reference, or even another formula.
Now let’s move on to some examples.
We’ll be evaluating exam grades. If the student obtained a score higher than or equal to 70, then we will return the message “Pass.” If the grade is lower than 70, then we will display “Fail.”
In this example, I have inserted the following formula in cell F9:=IF(E9>=70, "Pass", "Fail")
The 3 arguments for this IF formula are:
logical_test: E9>=70
value_if_true: Pass
is returned if E9>=70.
value_if_false: Fail
is returned if E9<70.
Please note that when you want to use text in your IF formulas (like a word or sentence), you need to wrap the text in quotes (e.g. “Fail”). The only exception is while using TRUE or FALSE, which are built-in functionalities that Excel recognizes automatically.
How to use the IF function in Excel with another function or formula
The beauty of the IF function is that it allows us to build complex financial models with lots of interdependencies. This includes using different formulas based on conditional logic.
In our next example, we will use the IF function to calculate a payment fee based on the value of the order. If the order value is higher than or equal to $1000, then it should calculate a payment fee of 1.00%. However, if the total order value is lower than $1000, then it should use 1.50%.
The formula in cell F31 is:=IF(E31>=1000, E31*1%, E31*1.5%)
Now let’s look at an IF formula that is dependent on user input. If we select free shipping for the order, then the shipping fee will be set to zero. Otherwise, it will be calculated as 3% of the order value.
This is something really easy to achieve, but it will open up so many opportunities for you to use the IF function in the future.
How to use nested IF statements in Excel
Nesting more IF functions allows you to perform multiple comparisons and create more complex formulas. However, you can only nest up to 64 IF functions in Excel. If you ever reach this limit (I never did), I can guarantee that there is a better and more elegant solution using functions like VLOOKUP, SUMIF, or COUNTIFS.
In the next example, I wrote a formula with several nested IF functions to assign a grade to a list of students based on their test results.
=IF(E71<60, "F", IF(E71<70, "D", IF(E71<80, "C", IF(E71<90, "B", "A"))))
The order of the conditions is important. When the conditions overlap, Excel will retrieve the [value_if_true] argument from the first IF statement that returns TRUE. This is why the conditions from the formula above need to be inserted in the same order for the formula to work properly.
Note: If you are running Office 365, then you can also look at the new IFS function. This function runs multiple tests and returns the value corresponding to the first TRUE result. It’s a very useful alternative to nested IF formulas and makes your formulas much easier to understand by others. You can read more about IFS on Microsoft’s website.
How to use IF formula with OR function in Excel
OR allows you to supply alternative conditions to an IF statement. This opens up opportunities to create complex scenarios where certain behavior is triggered by multiple possible conditions.
Let’s look at an IF formula that calculates a 2.00% shipping fee when the total order value is higher than $1000 or when there are more than 5 items in the order.
The IF OR statement I’ve used in cell H106 is:=IF(OR(G106>1000, F106>5), G106*2%, 0)
The OR function evaluates if G106>1000
or if F106>5
and the formula returns TRUE
when either or both conditions are fulfilled.
How to use IF formula with AND function in Excel
AND allows you to supply multiple criteria to an IF statement. Basically, the IF function returns TRUE if, and only if, all the conditions are met.
Working with our previous example, let’s apply the shipping fee only when the total order value is higher than $1000 and the order contains more than 5 items.
The IF AND statement I’ve used in cell H106 is:=IF(AND(G128>1000, F128>5), G128*2%, 0)
The AND function evaluates if G106>1000
and if F106>5
and returns TRUE
when both conditions are fulfilled.
How to use IF function with VLOOKUP in Excel
VLOOKUP can be nested inside an IF formula to retrieve data when a condition is TRUE or FALSE. In the next example, I will show you how to calculate shipping fees based on a different table that contains the thresholds and percentages to be applied depending on the order value.
The formula I’ve used in cell F152:=IF(G152="No", VLOOKUP(E152, $J$146:$K$152, 2, TRUE)*E152, 0)
The formula uses the following arguments:
logical_test: G152="No"
value_if_true: VLOOKUP(E152, $J$146:$K$152, 2, TRUE)*E152
is used to retrieve the corresponding shipping fee percentage when G152=”No”
value_if_false: 0
is returned if G152 is anything else than “No.” In our case, the alternative is selecting “Yes” from the drop-down list.
Note: One thing to remember is that I’ve used a VLOOKUP formula with an approximate match argument. This means that your data must be sorted in ascending order by lookup value (in our case, the Order amount).
In case you need additional help, please also read this article that explains step-by-step how to use VLOOKUP function in Excel.
What to do next?
IF is a versatile function that can be used in a wide range of scenarios. I use it daily, and I can’t imagine a world where Excel would lack this functionality.
Practice writing formulas using the IF function, and your spreadsheets will definitely get better and more complex. For example, why not look at another example using an IF function with 3 conditions? It will show you more examples of how to insert an if formula in Excel using nested IF statements and multiple conditions.
Let me know if you have questions on how to use IF function in Excel or if you need advice on how to nest multiple IF statements in your Excel project by leaving a comment below.
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.
Функция ЕСЛИ в Excel — это отличный инструмент для проверки условий на ИСТИНУ или ЛОЖЬ. Если значения ваших расчетов равны заданным параметрам функции как ИСТИНА, то она возвращает одно значение, если ЛОЖЬ, то другое.
Содержание
- Что возвращает функция
- Синтаксис
- Аргументы функции
- Дополнительная информация
- Функция Если в Excel примеры с несколькими условиями
- Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)
- Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения
- Пример 3. Вычисляем сумму комиссии с продаж с помощью функции IF (ЕСЛИ) в Excel
- Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel
- Пример 5. Преобразуем ошибки в значения “0” с помощью функции IF (ЕСЛИ)
Что возвращает функция
Заданное вами значение при выполнении двух условий ИСТИНА или ЛОЖЬ.
Синтаксис
=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 тыс.
Рассчитать размер комиссионных для торгового агента можно по следующей формуле:
=IF(B2<50,0,IF(B2<100,B2*2%,B2*4%)) — английская версия
=ЕСЛИ(B2<50;0;ЕСЛИ(B2<100;B2*2%;B2*4%)) — русская версия
В формуле, использованной в примере выше, вычисление суммы комиссионных выполняется в самой функции ЕСЛИ. Если объем продаж находится между 50-100K, то формула возвращает B2 * 2%, что составляет 2% комиссии в зависимости от объема продажи.
Больше лайфхаков в нашем Telegram Подписаться
Пример 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) — русская версия
What is IF Function in Excel?
IF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
For example, the IF formula in Excel can be applied as follows:
“=IF(condition A,“value B”,“value C”)”
The IF excel function returns “value B” if condition A is met and returns “value C” if condition A is not met.
It is often used to make logical interpretations which help in decision-making.
Table of contents
- What is IF Function in Excel?
- Syntax of the IF Excel Function
- How to Use IF Function in Excel?
- Example #1
- Example #2
- Example #3
- Example #4
- Example #5
- Guidelines for the Multiple IF Statements
- Frequently Asked Question
- IF Excel Function Video
- Recommended Articles
Syntax of the IF Excel Function
The syntax of the IF function is shown in the following image:
The IF excel function accepts the following arguments:
- Logical_test: It refers to the condition to be evaluated. The condition can be a value or a logical expression.
- Value_if_true: It is the value returned as a result when the condition is “true”.
- Value_if_false: It is the value returned as a result when the condition is “false”.
In the formula, the “logical_test” is a required argument, whereas the “value_if_true” and “value_if_false” are optional arguments.
The IF formula uses logical operators to evaluate the values in a range of cells. The following table shows the different logical operatorsLogical operators in excel are also known as the comparison operators and they are used to compare two or more values, the return output given by these operators are either true or false, we get true value when the conditions match the criteria and false as a result when the conditions do not match the criteria.read more and their meaning.
Operator | Meaning |
---|---|
= | Equal to |
> | Greater than |
>= | Greater than or equal to |
< | Less than |
<= | Less than or equal to |
<> | Not equal to |
How to Use IF Function in Excel?
Let us understand the working of the IF function with the help of the following examples in Excel.
You can download this IF Function Excel Template here – IF Function Excel Template
Example #1
If there is no oxygen on a planet, life is impossible. If oxygen is available on a planet, then life is possible. The following table shows a list of planets in column A and the information on the availability of oxygen in column B. We have to find the planets where life is possible, based on the condition of oxygen availability.
Let us apply the IF formula to cell C2 to find out whether life is possible on the planets listed in the table.
The IF formula is stated as follows:
“=IF(B2=“Yes”, “Life is Possible”, “Life is Not Possible”)
The succeeding image shows the IF formula applied to cell C2.
The subsequent image shows how the IF formula is applied to the range of cells C2:C5.
Drag the cells to view the output of all the planets.
The output in the below worksheet shows life is possible on the planet Earth.
Flow Chart of Generic IF Excel Function
The IF Function Flow Chart for Mars (Example #1)
The flow of IF function flowchart for Jupiter and Venus is the same as the IF function flowchart for Mars (Example #1).
The IF Function Flow Chart for Earth
Hence, the IF excel function allows making logical comparisons between values. The modus operandi of the IF function is stated as: If something is true, then do something; otherwise, do something else.
Example #2
The following table shows a list of years. We want to find out if the given year is a leap year or not.
A leap year has 366 days; the extra day is the 29th of February. The criteria for a leap year are stated as follows:
- The year will be exactly divisible by 4 and not exactly be divisible by 100 or
- The year will be exactly divisible by 400.
In this example, we will use the IF function along with the AND, OR, and MOD functions to find the leap years.
We use the MOD function to find a remainder after a dividend is divided by a divisor.
The AND functionThe AND function in Excel is classified as a logical function; it returns TRUE if the specified conditions are met, otherwise it returns FALSE.read more evaluates both the conditions of the leap years for the value “true”. The OR functionThe OR function in Excel is used to test various conditions, allowing you to compare two values or statements in Excel. If at least one of the arguments or conditions evaluates to TRUE, it will return TRUE. Similarly, if all of the arguments or conditions are FALSE, it will return FASLE.read more evaluates either of the condition for the value “true”.
We will apply the MOD function to the conditions as follows:
If MOD(year,4)=0 and MOD(year,100)<>(is not equal to) 0, then the year is a leap year.
or
If MOD(year,400)=0, then the year is a leap year; otherwise, the year is not a leap year.
The IF formula is stated as follows:
“=IF(OR(AND((MOD(year,4)=0),(MOD(year,100)<>0)),(MOD(year,400)=0)),“Leap Year”, “Not A Leap Year”)”
The argument “year” refers to a reference value.
The following images show the output of the IF formula applied in the range of cells.
The following image shows how the IF formula is applied to the range of cells B2:B18.
The succeeding table shows the years 1960, 2028, and 2148 as leap years and the remaining as non-leap years.
The result of the IF excel formula is displayed for the range of cells B2:B18 in the following image.
Example #3
The succeeding table shows a list of drivers and the directions they undertook to reach the destination. It is preceded by an image of the road intersection explaining the turns taken by the drivers and their destinations. The right turn leads to town B, and the left turn leads to town C. Identify the driver’s destination to town B and town C.
Road Intersection Image
Let us apply the IF excel function to find the destination. Here, the condition is mentioned as follows:
- If the driver turns right, he/she reaches town B.
- If the driver turns left, he/she reaches town C.
We use the following IF formula to find the destination:
“=IF(B2=“Left”, “Town C”, “Town B”)”
The succeeding image shows the output of the IF formula applied to cell C2.
Drag the cells to use the formula in the range C2:C11. Finally, we get the destinations of each driver for their turning movements.
The below image displays the IF formula applied to the range.
The output of the IF formula and the destinations are displayed in the succeeding image.
The result shows that six drivers reached town C, and the remaining four have reached town B.
Example #4
The following table shows a list of items and their inventory levels. We want to check if the specific item is available in the inventory or not using the IF function.
Let us list the name of items in column A and the number of items in column B. The list of data to be validated for the entire items list is shown in the cell E2 of the below image.
We use the Excel IF along with the VLOOKUP functionThe VLOOKUP excel function searches for a particular value and returns a corresponding match based on a unique identifier. A unique identifier is uniquely associated with all the records of the database. For instance, employee ID, student roll number, customer contact number, seller email address, etc., are unique identifiers.
read more to check the availability of the items in the inventory.
The VLOOKUP function looks up the values referring to the number of items, and the IF function will check whether the item number is greater than zero or not.
We will apply the following IF formula in the F2 cell:
“=IF(VLOOKUP(E2,A2:B11,2,0)=0, “Item Not Available”,“Item Available”)”
If the lookup value of an item is equal to 0, then the item is not available; else, the item is available.
The succeeding image shows the result of the IF formula in the cell F2.
Select “bat” in the E2 item cell to know whether the item is available or not in the inventory (as shown in the following image).
Example #5
The following table shows the list of students and their marks. The grade criteria are provided based on the marks obtained by the students. We want to find the grade of each student in the list.
We apply the Nested IF in Excel since we have multiple criteria to find and decide each student’s grade.
The Nesting of IF function uses the IF function inside another IF formula when multiple conditions are to be fulfilled.
The syntax of Nesting of IF function is stated as follows:
“=IF( condition1, value_if_true1, IF( condition2, value_if_true2, value_if_false2 ))”
The succeeding table represents the range of scores and the grades, respectively.
Let us apply the multiple IF conditions with AND function in the below-nested formula to find out the grade of the students:
“=IF((B2>=95),“A”,IF(AND(B2>=85,B2<=94),“B”,IF(AND(B2>=75,B2<=84),“C”,IF(AND(B2>=61,B2<=74),“D”,“F”))))”
The IF function checks the logical condition as shown in the formula below:
“=IF(logical_test, [value_if_true],[value_if_false])”
We will split the above-mentioned nested formula and check the IF statements as shown below:
First Logical Test: B2>=95
If the formula returns,
- Value_if_true, execute: “A” (Grade A) else(comma) enter value_if_false
- Value_if_false, then the formula finds another IF condition and enter IF condition
Second Logical Test: B2>=85(logical expression 1) and B2<=94(logical expression 2)
(We use AND function to check the multiple logical expressions as the two given conditions are to be evaluated for “true.”)
If the formula returns,
- Value_if_true, execute: “B” (Grade B) else(comma) enter value_if_false
- Value_if_false, then the formula finds another IF condition and enter IF condition
Third Logical Test: B2>=75(logical expression 1) and B2<=84(logical expression 2)
(We use AND function to check the multiple logical expressions as the two given conditions are to be evaluated for “true.”)
If the formula returns,
- Value_if_true, execute: “C” (Grade C) else(comma) enter value_if_false
- value_if_false, then the formula finds another IF condition and enter IF condition
Fourth Logical Test: B2>=61(logical expression 1) and B2<=74(logical expression 2)
(We use AND function to check the multiple logical expressions as the two given conditions are to be evaluated for “true.”)
If the formula returns,
- Value_if_true, execute: “D” (Grade D) else(comma) enter value_if_false
- Value_if_false, execute: “F” (Grade F)
- Finally, close the parenthesis.
The below image displays the output of the IF formula applied to the range.
The succeeding image shows the IF nested formula applied to the range.
The grades of the students are listed in the following table.
Guidelines for the Multiple IF Statements
The guidelines for the multiple IF statements are listed as follows:
- Use nested IF function to a limited extent as multiple IF statements require a great deal of thought to be accurate.
- Multiple IF statementsIn Excel, multiple IF conditions are IF statements that are contained within another IF statement. They are used to test multiple conditions at the same time and return distinct values. Additional IF statements can be included in the ‘value if true’ and ‘value if false’ arguments of a standard IF formula.read more require multiple parentheses (), which is often difficult to manage. Excel provides a way to check the color of each opening and closing parenthesis to avoid this situation. The last closing parenthesis color will always be black, denoting the end of the formula statement.
- Whenever we pass a string value for the arguments “value_if_true” and “value_if_false” or test a reference against a string value, enclose the string value in double quotes. Passing a string value without quotes will result in “#NAME?” error.
Frequently Asked Question
1. What is the IF function in Excel?
The Excel IF function is a logical function that checks the given criteria and returns one value for a “true” and another value for a “false” result.
The syntax of the IF function is stated as follows:
“=IF(logical_test, [value_if_true], [value_if_false])”
The arguments are as follows:
1. Logical_test – It refers to a value or condition that is tested.
2. Value_if_true – It is the value returned when the condition logical_test is “true.”
3. Value_if_false – It is the value returned when the condition logical_test is “false.”
The “logical_test” is a required argument, whereas the “value_if_true” and “value_if_false” are optional arguments.
2. How to use the IF Excel function with multiple conditions?
The IF Excel statement for multiple conditions is created by using multiple IF functions in a single formula.
The syntax of IF function with multiple conditions is stated as follows:
“=IF (condition 1_“true”, do something, IF (condition 2_“true”, do something, IF (condition 3_ “true”, do something, else do something)))”
3. How to use the function IFERROR in Excel?
IF Excel Function Video
Recommended Articles
This has been a guide to the IF function in Excel. Here we discuss how to use the IF function along with examples and downloadable templates. You may also look at these useful functions –
- What is the Logical Test in Excel?A logical test in Excel results in an analytical output, either true or false. The equals to operator, “=,” is the most commonly used logical test.read more
- “Not Equal to” in Excel“Not Equal to” argument in excel is inserted with the expression <>. The two brackets posing away from each other command excel of the “Not Equal to” argument, and the user then makes excel checks if two values are not equal to each other.read more
- Data Validation ExcelThe data validation in excel helps control the kind of input entered by a user in the worksheet.read more
This tutorial demonstrates how to use the IF Function in Excel and Google Sheets to create If Then Statements.
IF Function Overview
The IF Function Checks whether a condition is met. If TRUE do one thing, if FALSE do another.
How to Use the IF Function
Here’s a very basic example so you can see what I mean. Try typing the following into Excel:
=IF( 2 + 2 = 4,"It’s true", "It’s false!")
Since 2 + 2 does in fact equal 4, Excel will return “It’s true!”. If we used this:
=IF( 2 + 2 = 5,"It’s true", "It’s false!")
Now Excel will return “It’s false!”, because 2 + 2 does not equal 5.
Here’s how you might use the IF statement in a spreadsheet.
=IF(C4-D4>0,C4-D4,0)
You run a sports bar and you set individual tab limits for different customers. You’ve set up this spreadsheet to check if each customer is over their limit, in which case you’ll cut them off until they pay their tab.
You check if C4-D4 (their current tab amount minus their limit), is greater than 0. This is your logical test. If this is true, IF returns “Yes” – you should cut them off. If this is false, IF returns “No” – you let them keep drinking.
What can IF Return?
Above we returned a text string, “Yes” or “No”. But you can also return numbers, or even other formulas.
Let’s say some of your customers are running up big tabs. To discourage this, you’re going to start charging interest on customers who go over their limit.
You can use IF for that:
=IF(C4>D4,C4*0.03,0)
If the tab is higher than the limit, return the tab multiplied by 0.03, which returns 3% of the tab. Otherwise, return 0: they aren’t over their tab, so you won’t charge interest.
Using IF with AND
You can combine IF with Excel’s AND Function to test more than one condition. Excel will only return TRUE if ALL of the tests are true.
So, you implemented your interest rate. But some of your regulars are complaining. They’ve always paid their tabs in the past, why are you cracking down on them now? You come up with a solution: you won’t charge interest to certain trusted customers.
You make a new column to your spreadsheet to identify trusted customers, and update your IF statement with an AND function:
=IF(AND(C4>D4, F4="No"),C4*0.03,0)
Let’s look at the AND part separately:
AND(C4>D4, F4="No")
Note the two conditions:
- C4>D4: checking if they’re over their tab limit, as before
- F4=”No”: this is the new bit, checking if they are not a trusted customer
So now we only return the interest rate if the customer is over their tab, AND we have “No” in the trusted customer column. Your regulars are happy again.
Using IF with OR
The OR Function allows you to test more than one condition, returning TRUE if any conditions are met.
Maybe customers being over their tab is not the only reason you’d cut them off. Maybe you give some people a temporary ban for other reasons, gambling on the premises perhaps.
So you add a new column to identify banned customers, and update your “Cut off?” column with an OR test:
=IF(OR(C4>D4,E4="Yes"),"Yes","No")
Looking just at the OR part:
OR(C4>D4,E4="Yes")
There are two conditions:
- C4>D4: checking if they’re over their tab limit
- F4=”Yes”: the new part, checking if they are currently banned
This will evaluate to true if they are over their tab, or if there is a “Yes” in column E. As you can see, Harry is cut off now, even though he’s not over his tab limit.
Using IF with XOR
The XOR Function returns TRUE if only one condition is met. If more than one condition is met (or not conditions are met). It returns FALSE.
An example might make this clearer. Imagine you want to start giving monthly bonuses to your staff :
- If they sell over $800 in food, or over $800 in drinks, you’ll give them a half bonus
- If they sell over $800 in both, you’ll give them a full bonus
- If they sell under $800 in both, they don’t get any bonus.
You already know how to work out if they get the full bonus. You’d just use IF with AND, as described earlier.
=IF(AND(C4>800,D4>800),"Yes","No")
But how would you work out who gets the half bonus? That’s where XOR comes in:
=IF(XOR(C4>=800,D4>=800),"Yes","No")
As you can see, Woody’s drink sales were over $800, but not food sales. So he gets the half bonus. The reverse is true for Coach. Diane and Carla sold more than $800 for both, so they don’t get a half bonus (both arguments are TRUE), and Rebecca made under the threshold for both (both arguments FALSE), so the formula again returns “No”.
Using IF with NOT
The NOT Function reverses the outcome of a logical test. In other words, it checks whether a condition has not been met.
You can use it with IF like this:
=IF(AND(C3>=1985,NOT(D3="Steven Spielberg")),"Watch", "Don’t Watch")
Here we have a table with data on some 1980s movies. We want to identify movies released on or after 1985, that were not directed by Steven Spielberg.
Because NOT is nested within an AND Function, Excel will evaluate that first. It will then use the result as part of the AND.
Nested IF Statements
You can also return an IF statement within your IF statement. This enables you to make more complex calculations.
Let’s go back to our customers table. Imagine you want to classify customers based on their debt level to you:
- $0: None
- Up to $500: Low
- $500 to $1000: Medium
- Over $1000: High
You can do this by “nesting” IF statements:
=IF(C4=0,"None",IF(C4<=500,"Low",IF(C4<=1000,"Medium",IF(C4>1000,"High"))))
It’s easier to understand if you put the IF statements on separate lines (ALT + ENTER on Windows, CTRL + COMMAND + ENTER on Macs):
=
IF(C4=0,"None",
IF(C4<=500,"Low",
IF(C4<=1000,"Medium",
IF(C4>1000,"High", "Unknown"))))
IF C4 is 0, we return “None”. Otherwise, we move to the next IF statement. IF C4 is equal to or less than 500, we return “Low”. Otherwise, we move on to the next IF statement… and so on.
Simplifying Complex IF Statements with Helper Columns
If you have multiple nested IF statements, and you’re throwing in logic functions too, your formulas can become very hard to read, test, and update.
This is especially important to keep in mind if other people will be using the spreadsheet. What makes sense in your head, might not be so obvious to others.
Helper columns are a great way around this issue.
You’re an analyst in the finance department of a large corporation. You’ve been asked to create a spreadsheet that checks whether each employee is eligible for the company pension.
Here’s the criteria:
So if you’re under the age of 55, you need to have 30 years’ service under your belt to be eligible. If you’re aged 55 to 59, you need 15 years’ service. And so on, up to age 65, where you’re eligible no matter how long you’ve worked there.
You could use a single, complex IF statement to solve this problem:
=IF(OR(F4>=65,AND(F4>=62,G4>=5),AND(F4>=60,G4>=10),AND(F4>=55,G4>=15),G4>30),"Eligible", "Not Eligible")
Whew! Kinda hard to get your head around that, isn’t it?
A better approach might be to use helper columns. We have five logical tests here, corresponding to each row in the criteria table. This is easier to see if we add line breaks to the formula, as we discussed earlier:
=IF(
OR(
F4>=65,
AND(F4>=62,G4>=5),
AND(F4>=60,G4>=10),
AND(F4>=55,G4>=15),
G4>30
),"Eligible","Not Eligible")
So, we can split these five tests into separate columns, and then simply check whether any one of them is true:
Each column in the table from E to I holds each of our criteria separately. Then in J4 we have the following formula:
=IF(COUNTIF(E4:I4,TRUE),"Eligible","Not Eligible")
Here we have an IF statement, and the logical test uses COUNTIF to count the number of cells within E4:I4 that contain TRUE.
If COUNTIF doesn’t find a TRUE value, it will return 0, which IF interprets as FALSE, so the IF returns “Not Eligible”.
If COUNTIF does find any TRUE values, it will return the number of them. IF interprets any number other than 0 as TRUE, so it returns “Eligible”.
Splitting out the logical tests in this way makes the formula easier to read, and if something’s going wrong with it, it’s much easier to spot where the mistake is.
Using Grouping to Hide Helper Columns
Helper columns make the formula easier to manage, but once you’ve got them in place and you know they are working correctly, they often just take up space on your spreadsheet without adding any useful information.
You could hide the columns, but this can lead to problems because hidden columns are hard to detect, unless you look closely at the column headers.
A better option is grouping.
Select the columns you want to group, in our case E:I. Then press ALT + SHIFT + RIGHT ARROW on Windows, or COMMAND + SHIFT + K on Mac. You can also go to the “Data” tab on the ribbon and select “Group” from the “Outline” section.
You’ll see the group displayed above the column headers, like this:
Then simply press the “-“ button to hide the columns:
The IFS Function
Nested IF statements are very useful when you need to perform more complex logical comparisons, and you need to do it in one cell. However, they can get complicated as they get longer, and they can be hard to read and update on your screen.
From Excel 2019 and Excel 365, Microsoft introduced another function, the IFS Function, to help make this a bit easier to manage. The nested IF example above could be achieved with IFS like this:
=IFS(
C4=0,"None",
C4<=500,"Low",
C4<=1000,"Medium",
C4>1000,"High",
TRUE, "Unknown",
)
You can read all about it on the main page for the Excel IFS Function <<link>>.
Using IF with Conditional Formatting
Excel’s Conditional Formatting feature enables you to format a cell in different ways depending on its contents. Since the IF returns different values based on our logical test, we might want to use Conditional Formatting with the IF Function to make these different values easier to see.
So let’s go back to our staff bonus table from earlier.
We’re returning “Yes” or “No” depending on what bonus we want to give. This tells us what we need to know, but the information doesn’t jump out at us. Let’s try to fix that.
Here’s how you’d do it:
- Select the cell range containing your IF statements. In our case that’s E4:F8.
- Click “Conditional Formatting” on the “Styles” section of the “Home” tab on the ribbon.
- Click “Highlight Cells Rules” and then “Equal to”.
- Type “Yes” (or whatever return value you need) into the first box, and then choose the formatting you want from the second box. (I’ll choose green for this).
- Repeat for all your return values (I’ll also set “No” values to red)
Here’s the result:
Using IF in Array Formulas
An array is a range of values, and in Excel arrays are represented as comma separated values enclosed in braces, such as:
{1,2,3,4,5}
The beauty of arrays, is that they enable you to perform a calculation on each value in the range, and then return the result. For example, the SUMPRODUCT Function takes two arrays, multiplies them together, and sums the results.
So this formula:
=SUMPRODUCT({1,2,3},{4,5,6})
…returns 32. Why? Let’s work it through:
1 * 4 = 4
2 * 5 = 10
3 * 6 = 18
4 + 10 + 18 = 32
We can bring an IF statement into this picture, so that each of these multiplications only happens if a logical test returns true.
For example, take this data:
If you wanted to calculate the total commission for each sales manager, you’d use the following:
=SUMPRODUCT(IF($C$2:$C$10=$G2,$D$2:$D$10*$E$2:$E$10))
Note: In Excel 2019 and earlier, you have to press CTRL + SHIFT + ENTER to turn this into an array formula.
We’d end up with something like this:
Breaking this down, the “Manager” column is column C, and in this example, Olivia’s name is in G2.
So the logical test is:
$C$2:$C$10=$G2
In English, if the name in column C is equal to what’s in G2 (“Olivia”), DO multiply the values in columns D and E for that row. Otherwise, don’t multiply them. Then, sum all the results.
You can learn more about this formula on the main page for the SUMPRODUCT IF Formula.
IF in Google Sheets
The IF Function works exactly the same in Google Sheets as in Excel:
VBA IF Statements
You can also use If Statements in VBA. Click the link to learn more, but here is a simple example:
Sub Test_IF ()
If Range("a1").Value < 0 then
Range("b1").Value = "Negative"
End If
End Sub
This code will test if a cell value is negative. If so, it will write “negative” in the next cell.
The logical IF statement in Excel is used for the recording of certain conditions. It compares the number and / or text, function, etc. of the formula when the values correspond to the set parameters, and then there is one record, when do not respond — another.
Logic functions — it is a very simple and effective tool that is often used in practice. Let us consider it in details by examples.
The syntax of the function «IF» with one condition
The operation syntax in Excel is the structure of the functions necessary for its operation data.
=IF(boolean;value_if_TRUE;value_if_FALSE)
Let us consider the function syntax:
- Boolean – what the operator checks (text or numeric data cell).
- Value_if_TRUE – what will appear in the cell when the text or numbers correspond to a predetermined condition (true).
- Value_if_FALSE – what appears in the box when the text or the number does not meet the predetermined condition (false).
Example:
Logical IF functions.
The operator checks the A1 cell and compares it to 20. This is a «Boolean». When the contents of the column is more than 20, there is a true legend «greater 20». In the other case it’s «less or equal 20».
Attention! The words in the formula need to be quoted. For Excel to understand that you want to display text values.
Here is one more example. To gain admission to the exam, a group of students must successfully pass a test. The results are listed in a table with columns: a list of students, a credit, an exam.
The statement IF should check not the digital data type but the text. Therefore, we prescribed in the formula В2= «done» We take the quotes for the program to recognize the text correctly.
The function IF in Excel with multiple conditions
Usually one condition for the logic function is not enough. If you need to consider several options for decision-making, spread operators’ IF into each other. Thus, we get several functions IF in Excel.
The syntax is as follows:
Here the operator checks the two parameters. If the first condition is true, the formula returns the first argument is the truth. False — the operator checks the second condition.
Examples of a few conditions of the function IF in Excel:
It’s a table for the analysis of the progress. The student received 5 points:
- А – excellent;
- В – above average or superior work;
- C – satisfactory;
- D – a passing grade;
- E – completely unsatisfactory.
IF statement checks two conditions: the equality of value in the cells.
In this example, we have added a third condition, which implies the presence of another report card and «twos». The principle of the operator is the same.
Enhanced functionality with the help of the operators «AND» and «OR»
When you need to check out a few of the true conditions you use the function И. The point is: IF A = 1 AND A = 2 THEN meaning в ELSE meaning с.
OR function checks the condition 1 or condition 2. As soon as at least one condition is true, the result is true. The point is: IF A = 1 OR A = 2 THEN value B ELSE value C.
Functions AND & OR can check up to 30 conditions.
An example of using the operator AND:
It’s the example of using the logical operator OR.
How to compare data in two tables
Users often need to compare the two spreadsheets in an Excel to match. Examples of the «life»: compare the prices of goods in different bringing, to compare balances (accounting reports) in a few months, the progress of pupils (students) of different classes, in different quarters, etc.
To compare the two tables in Excel, you can use the COUNTIFS statement. Consider the order of application functions.
For example, consider the two tables with the specifications of various food processors. We planned allocation of color differences. This problem in Excel solves the conditional formatting.
Baseline data (tables, which will work with):
Select the first table. Conditional Formatting — create a rule — use a formula to determine the formatted cells:
In the formula bar write: = COUNTIFS (comparable range; first cell of first table)=0. Comparing range is in the second table.
To drive the formula into the range, just select it first cell and the last. «= 0» means the search for the exact command (not approximate) values.
Choose the format and establish what changes in the cell formula in compliance. It’s better to do a color fill.
Select the second table. Conditional Formatting — create a rule — use the formula. Use the same operator (COUNTIFS). For the second table formula:
Download all examples in Excel
Now it is easy to compare the characteristics of the data in the table.
Download Article
Download Article
One of the most useful features of Microsoft Excel is the IF-THEN statement, which is used to perform calculations or display text based on whether a condition is true. If you’re confused about the IF function, this handy wikiHow tutorial will guide you through writing useful IF-THEN formulas, from making simple comparisons to testing multiple conditions. Read on for examples, troubleshooting tips, and more!
-
=IF(logical_test, value_if_true, value_if_false). An IF statement makes a logical comparison based on whether a condition is true or false.
- logical_test: This is the condition that you want to test (required).
- value_if_true: The value you want returned if logical_test is true (required).
- value_if_false: The value you want returned if logical_test is not true (optional).
Advertisement
-
1
=IF(B3>C3, «Goal Met», «Goal Not Met»).
- In this example, the condition is B3>C3, meaning «If the value of B3 is greater than C3.»
- If the value of B3 is greater than C3, then Goal Met will appear in the cell.
- If the value of B3 is less than the value of C3, then Goal Not Met will appear in the cell.
-
2
=IF(B3=C3, «Goal Met»).
- In this example, the condition is B3=C3, meaning, «If the value of B3 is equal to the value of C3.»
- If the values are equal, «Goal Met» will appear in the cell.
- If the values are not equal, a zero will appear in the field because we did not define a third (ELSE) value.[1]
-
3
=IF(B3*2>C3, C3*400, «Good»).
- In this example the condition is B3*2>C3, meaning «If the value of B3 multiplied by 2 is greater than the value of C3.»
- If the value of B3*2 is greater than the value of C3, the value of C3 multiplied by 400 will appear in this cell.
- If the value of B3*2 is not greater than the value of C3, the word «Good» will appear in the cell.
-
4
=IF(B3=»Sold», «1», «»)
- In this example, the condition is B3="Sold", meaning «If the value of cell B3 contains the word Sold.»
- If B3 contains the word «Sold,» a «1» will appear in the cell.
- If B3 says anything other than the word «Sold,» the condition is false. Since our ELSE value is " ", which is two double quote marks with nothing in between, the cell value will be blank.
-
5
=IF(D3=»Taxed», F3*.07, «0»).
- In this example, the condition is D3="Taxed", meaning «If the value of D3 is the word Taxed.»
- If D3 contains the word «Taxed,» the result will be the value of F3 multiplied by .07.
- If D3 contains anything other than the word «Taxed,» the result will be 0.
-
6
Things to remember.
- An IF statement can have two different results—one result if the condition is true, and another result if the condition is false.
- The ELSE value, which is what will happen if the result is false, is optional—if you don’t specify what to place in the cell if the condition is false, a «0» will appear in the cell. If you’d rather the cell be blank, make your ELSE value "".
- When referring to specific text in a condition or THEN/ELSE value, always surround that text in quotation marks.
Advertisement
-
1
You can nest up to 64 IF/THEN statements in a single formula. For example, let’s say you want to create a formula that calculates sales tax for purchases made from Alaska, California, Oregon, and Washington. Since each of these four states has its own tax rate, we’ll need to create a formula that contains four IF/THEN statements to test four conditions. Assuming the sale amount is in G1 and the purchaser’s state is in F1, our formula would look like this, using the 2022 tax rates for these 4 states:
- =IF(F1=»Alaska», G1*0,IF(F1=»California»,G1*0.0725,IF(F1=»Oregon»,G1*0,IF(F1=»Washington», G1*0.065))))
-
2
Nesting many IF/THEN statements can be challenging. Aside from the very long formulas, creating very long IF/THEN statements may become cumbersome if you have to frequently change them. In our previous example, we’d need to update our IF/THEN statements any time a state’s tax rate changed.
- A good alternative to IF/THEN statements in this situation would be to add the values to a single table and use a VLOOKUP formula to query the table for the proper rates.
- For example, if we add a list of our states to column A and their corresponding tax rates in column B, we could write a VLOOKUP formula that does the math for us without specifying the amounts in the formula itself. The shortened version of the above nested IF/THEN formula would be =G1*VLOOKUP(F1,A:B,2,TRUE).
- If you had to update a tax rate, you’d now only have to update it in the referenced table, not all of your formulas.
Advertisement
-
1
The result is zero (0). This means that you didn’t specify a value for either the value_if_true or value_if_false arguments.[2]
- If you don’t specify a value_if_false value, the result will always be 0 if the condition is false.
-
2
The result is the #NAME? error. This indicates that a syntax error—make sure you’ve surrounded the formula after = with parentheses, your arguments are separated by commas, and that any plain text is surrounded by quotation marks.
- For example, this IF/THEN statement will result in the #NAME? error because there are no quotation marks around the value OK: =IF(A2>1,OK).
- The correct syntax would be =IF(A2>1,"OK")
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
References
About This Article
Article SummaryX
1. The syntax for an IF-THEN statement is =IF(logical_test, value_if_true, value_if_false).
2. «logical_test» is the condition you want to test, such as whether a cell value is greater than or equal to another cell.
3. «value_if_true» is what the formula should do if the test condition is true.
4. «value_if_false» is what the formula should do if the test condition is «not» true.
Did this summary help you?
Thanks to all authors for creating a page that has been read 48,324 times.
Is this article up to date?
Bottom Line: Learn how to use the IF Function to write formulas that return results based on a condition or logical test. This post includes training on logical tests, comparison operators, nested IF formulas, multiple conditions with AND and OR functions, and common causes of formula errors.
Skill Level: Beginner
Watch the Tutorial
Download the Excel File
You can access the file that I use in the video by clicking below.
Mastering the IF Function
The IF Function is an important function to know. It can help with comparing data, performing lookups to group data, and making reports interactive. If you’re not familiar with IF or could use a refresher, this post will help.
Here is the IF function’s signature:
=IF(logical_test, [value_if_true], [value_if_false])
The IF Function has 3 arguments:
- Logical test. This is where we can compare data or see if a condition is met.
- Value if true. Defining this argument tells Excel to return a certain value if the condition in the logical test is met.
- Value if false. If the condition is not met, this argument defines what the returned value will be.
Here’s an example. I’m comparing Revenue amounts with Goal amounts. If the Revenue is greater than or equal to the goal, I want column D to say Yes, and if not, to say No.
Let’s talk about the most important part of the IF function: the logical test.
Logical Tests
The logical test portion of the formula always uses a comparison operator to compare values and determine if the statement is true or false. Here is a list of comparison operators that can be used.
Operator | Description |
---|---|
= | Equal To |
<> | Not Equal To |
> | Greater Than |
< | Less Than |
>= | Greater Than or Equal To |
<= | Less Than or Equal To |
Logical tests return TRUE or FALSE values. This is important because the logical test argument within IF needs a TRUE or FALSE (boolean) value returned to it. It is also important because you might not even need an IF function if the TRUE/FALSE values can be used to get the answer you are looking for.
It’s also important to note that the case doesn’t matter when comparing text. The following formula will return TRUE.
=”Excel Campus” = “excel campus”
Returning Other Values
While “TRUE” and “FALSE” would probably be sufficient for my example, I prefer them to say “Yes” and “No” in answer to the question in by column header: “Hit goal?”.
The advantage of using an IF function is that you can return any values you like by specifying the words that you want to appear. Just make sure to wrap them in quotation marks when writing your IF formula, unless they are numbers. If you do not specify these second and third arguments when writing the IF formula, it will simply return TRUE and FALSE.
The value_if_true and value_if_false arguments can contain just about anything:
- A number
- Text wrapped in double quotes – “hello”
- A reference to another cell – A2
- A formula with another IF function.
- A formula with any other combination of functions.
It’s also important to note that both the value_if_true and value_if_false arguments are optional. This is denoted by the square brackets around them in the function signature.
You must specify at least one of the arguments. If you leave one of the arguments blank and the logical test results in that condition, then a TRUE or FALSE value will be returned to the cell.
For example, the following formula will return a FALSE if A2 does NOT equal B2 because the value_if_false argument is not specified.
=IF(A2=B2, "Match")
Grouping Data
One common use for the IF Function is to categorize data. Let me show you an example.
On this worksheet, I want to categorize transactions as either Large or Small depending on the amount I’ve entered in cell D4. A transaction less than $60,000 will be labeled as small. Transactions greater than or equal to $60,000 will be large.
When writing the formula, I could specify the amounts and the labels by typing them out, but I prefer to use cell references so that they can quickly and easily be updated without rewriting the formulas.
The dollar symbols ($) in the formula make the references absolute so that they don’t change when the formula is copied down to the cells below it. When the cell reference within the formula is selected, you can hit F4 on your keyboard (for Fn + F4 for most laptop keyboards) to insert a dollar symbol before the row number and column letter. (Pressing it repeatedly will toggle it to one or the other and back again to none or both.)
Categorizing these transactions is helpful for analyzing the data. You can filter out just the large or small items, or you can use these labels in a summary report, pivot table, or chart. Below is an example.
Multiple Logical Tests
If we want to use more than one logical test, we can use the AND and OR Functions.
The AND Function
The AND Function checks whether all arguments are true and returns TRUE if they are.
In the example below, our formula is looking for transactions that are both “Large” and “Product 6.”
The OR Function
Perhaps you want show a positive result if only ONE of the logical tests in your formula is true, not BOTH. If that is the case, you can use the OR Function.
The OR Function checks whether any of the arguments are true, and returns TRUE or FALSE. It returns FALSE only if all arguments are false.
Using the same sheet as above, the formula in our example below is looking for entries where the size is “Large” OR if the product name is “Product 5.”
If we want to return text or a number instead of TRUE or FALSE, then we can wrap the AND or OR Functions in the IF Function. For example, using the OR Function above as our logical test in an IF Formula, we can type the word Upgrade (in parentheses) as our Value If True argument. That means, when the conditions we’ve specified are true, the cell will say Upgrade. To return a blank cell when the conditions aren’t met, we just have two quotation marks with nothing between them for our Value If False argument.
Nested IF Formulas
Things can get more complicated when there are more categories added to the mix. Maybe you want to group data based on 3 or more logical tests in your IF formula.
When this happens, we end up nesting another IF Function into our existing function each time we add another category.
For example, let’s say we have three account categories called Small, Large, and Key. A Small account is less than $10,000. A Large account is between $10,000 and $70,000. And a Key account is more than $70,000.
When we write our formula to categorize these accounts, we will need to use two IF statements, with one nested within the other.
The logic of the formula goes like this.
- If the amount is greater than or equal to $70,000, return a value of “Key.”
- But if it’s NOT, evaluate the next IF Function.
- If the amount is greater than or equal to $10,000, return a value of “Large.”
- But if it’s NOT, return a value of “Small.”
With the cell references plugged in for the sizes and amounts, the formula would look like this on our spreadsheet.
As you can imagine, these nested IF formulas can get longer and uglier with each additional category or criteria that is added. That being the case, there are a couple of alternatives that I would like to mention.
Alternative 1: The IFS Function
This is a relatively new function introduced in Excel 2019. While it still requires a lot of selection and logical tests, it is somewhat easier to read and write the IFS formula compared to nested IF formulas.
I won’t go into detail about writing the IFS Function, but you can play around with it in the Excel file attached at the top of this post.
Alternative 2: Lookup Formulas
You can use VLOOKUP, XLOOKUP, or Index Match to return the same results as the nested IFs. These are a lot simpler to write. For an explanation of how to write a VLOOKUP formula like this, jump over to this tutorial:
How to Use VLOOKUP to Find the Closest Match – Last Argument is TRUE
Common Errors with the IF Function
If you come across errors when using the IF Function, it is most likely related to data types. What I mean by that is, Excel can’t compare text to a number or a date, or evaluate text that is different. However, the formatting of values doesn’t hinder Excel from making comparisons in logical tests. Below you can see how the values in Column A and Column B return a TRUE or FALSE in column C when they are compared.
Note that while the entry in B9 looks like it is formatted as a date, it is formatted as text. That is why it is returning FALSE when compared to the date in A9. See the video above for a further explanation on errors with data types.
Related Posts
If you found this information helpful, check out these other tutorials on related content.
- How to Calculate Commissions in Excel with VLOOKUP, XLOOKUP, or IF
- Introduction to Pivot Tables and Dashboards
- Excel Tables Tutorial Video – Beginners Guide for Windows & Mac
Conclusion
Ready for a challenge? Test what you’ve learned and get more practice by taking our free IF Formula Challenge! You can access it here:
The challenge includes videos that explain the challenge and walk through the solution. See if you can earn all six gold stars in the challenge file.
I hope this explanation has been helpful and that you start putting the IF Function to work in your spreadsheets soon if you’re not already using it. Leave a comment below if you have questions or feedback!