Formula for if function in excel

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).

Your browser does not support video. Install Microsoft Silverlight, Adobe Flash Player, or Internet Explorer 9.

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

Cell D2 contains a formula =IF(C2="Yes",1,2)

  • =IF(C2=”Yes”,1,2)

In the above example, cell D2 says: IF(C2 = Yes, then return a 1, otherwise return a 2)

Cell D2 contains the formula =IF(C2=1,"YES","NO")

  • =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.

Formula in cell D2 is =IF(C2>B2,”Over Budget”,”Within Budget”)

  • =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”)

Formula in cell E2 is =IF(C2>B2,C2-B2,"")

  • =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).

Formula in Cell F7 is IF(E7=”Yes”,F5*0.0825,0)

  • =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.

Connect with an expert. Learn from live instructors.

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.

Функция ЕСЛИ в Excel — это отличный инструмент для проверки условий на ИСТИНУ или ЛОЖЬ. Если значения ваших расчетов равны заданным параметрам функции как ИСТИНА, то она возвращает одно значение, если ЛОЖЬ, то другое.

Содержание

  1. Что возвращает функция
  2. Синтаксис
  3. Аргументы функции
  4. Дополнительная информация
  5. Функция Если в Excel примеры с несколькими условиями
  6. Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)
  7. Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения
  8. Пример 3. Вычисляем сумму комиссии с продаж с помощью функции IF (ЕСЛИ) в Excel
  9. Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel
  10. Пример 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 (ИСТИНА).

    IF-EXCEL-01|
  • Если вы не укажете условие аргумента TRUE(ИСТИНА) (value_if_true (значение_если_истина)) в функции, т.е. условие указано только для аргумента value_if_false (значение_если_ложь), то формула вернет значение “0”, если результат вычисления функции будет равен TRUE (ИСТИНА);
    На примере ниже формула равна =IF (A1>20;«Отказать») или =ЕСЛИ(A1>20;»Отказать»), где аргумент value_if_true (значение_если_истина) не указан, формула будет возвращать “0” всякий раз, когда условие соответствует TRUE (ИСТИНА).

IF EXCEL - 02

Функция Если в Excel примеры с несколькими условиями

Пример 1. Проверяем простое числовое условие с помощью функции IF (ЕСЛИ)

При использовании функции ЕСЛИ в Excel, вы можете использовать различные операторы для проверки состояния. Вот список операторов, которые вы можете использовать:

IF-EXCEL-03

Ниже приведен простой пример использования функции при расчете оценок студентов. Если сумма баллов больше или равна «35», то формула возвращает “Сдал”, иначе возвращается “Не сдал”.

Excel-IF-04

Пример 2. Использование вложенной функции IF (ЕСЛИ) для проверки условия выражения

Функция может принимать до 64 условий одновременно. Несмотря на то, что создавать длинные вложенные функции нецелесообразно, то в редких случаях вы можете создать формулу, которая множество условий последовательно.

В приведенном ниже примере мы проверяем два условия.

  • Первое условие проверяет, сумму баллов не меньше ли она чем 35 баллов. Если это ИСТИНА, то функция вернет “Не сдал”;
  • В случае, если первое условие — ЛОЖЬ, и сумма баллов больше 35, то функция проверяет второе условие. В случае если сумма баллов больше или равна 75. Если это правда, то функция возвращает значение “Отлично”, в других случаях функция возвращает “Сдал”.

Excel-If-06

Пример 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%)) — русская версия

Excel-IF-07

В формуле, использованной в примере выше, вычисление суммы комиссионных выполняется в самой функции ЕСЛИ. Если объем продаж находится между 50-100K, то формула возвращает B2 * 2%, что составляет 2% комиссии в зависимости от объема продажи.

Telegram Logo Больше лайфхаков в нашем Telegram Подписаться

Пример 4. Используем логические операторы (AND/OR) (И/ИЛИ) в функции IF (ЕСЛИ) в Excel

Вы можете использовать логические операторы (AND/OR) (И/ИЛИ) внутри функции для одновременного тестирования нескольких условий.

Например, предположим, что вы должны выбрать студентов для стипендий, основываясь на оценках и посещаемости. В приведенном ниже примере учащийся имеет право на участие только в том случае, если он набрал более 80 баллов и имеет посещаемость более 80%.

Excel-If-09

Вы можете использовать функцию AND (И) вместе с функцией IF (ЕСЛИ), чтобы сначала проверить, выполняются ли оба эти условия или нет. Если условия соблюдены, функция возвращает “Имеет право”, в противном случае она возвращает “Не имеет право”.

Формула для этого расчета:

=IF(AND(B2>80,C2>80%),”Да”,”Нет”) — английская версия

=ЕСЛИ(И(B2>80;C2>80%);»Да»;»Нет») — русская версия

Excel-IF-10

Пример 5. Преобразуем ошибки в значения “0” с помощью функции IF (ЕСЛИ)

С помощью этой функции вы также можете убирать ячейки содержащие ошибки. Вы можете преобразовать значения ошибок в пробелы или нули или любое другое значение.

Формула для преобразования ошибок в ячейках следующая:

=IF(ISERROR(A1),0,A1) — английская версия

=ЕСЛИ(ЕОШИБКА(A1);0;A1) — русская версия

Формула возвращает “0”, в случае если в ячейке есть ошибка, иначе она возвращает значение ячейки.

ПРИМЕЧАНИЕ. Если вы используете Excel 2007 или версии после него, вы также можете использовать функцию IFERROR для этого.

Точно так же вы можете обрабатывать пустые ячейки. В случае пустых ячеек используйте функцию ISBLANK, на примере ниже:

=IF(ISBLANK(A1),0,A1) — английская версия

=ЕСЛИ(ЕПУСТО(A1);0;A1) — русская версия

EXCEL-IF-11

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:

Excel IF Formula

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.

IF Function Example 1

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.

IF Function Example 1-2

The subsequent image shows how the IF formula is applied to the range of cells C2:C5.

IF Function Example 1-4

Drag the cells to view the output of all the planets.

IF Function Example 1-3

The output in the below worksheet shows life is possible on the planet Earth.

Flow Chart of Generic IF Excel Function

Flow Chart of IF Function

The IF Function Flow Chart for Mars (Example #1)

Flow Chart of IF Function 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

Flow Chart of IF Function 2

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:

  1. The year will be exactly divisible by 4 and not exactly be divisible by 100 or
  2. The year will be exactly divisible by 400.

IF Function Example 2

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.

IF Function Example 2-1

IF Function Example 2-2

The following image shows how the IF formula is applied to the range of cells B2:B18.

IF Function Example 2-4

The succeeding table shows the years 1960, 2028, and 2148 as leap years and the remaining as non-leap years.

IF Function Example 2-3

The result of the IF excel formula is displayed for the range of cells B2:B18 in the following image.

IF Function Example 2-5

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

IF Function (Destination Example)

IF Function Example 3-1

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.

IF Function Example 3-2

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.

IF Function Example 3-3

The output of the IF formula and the destinations are displayed in the succeeding image.

IF Function Example 3-4

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.

Example 4

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.

Example 4-1

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.

Example 4-2

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 4-3

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.

Example 4-4

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.

Example 4-5

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.

Example 4-6

The succeeding image shows the IF nested formula applied to the range.

Example 4-7

The grades of the students are listed in the following table.

Example 4-8

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 formula main

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)

How to use IF

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)

Return Formula

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)

IF AND

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")

if formula or function

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")

IF XOR A

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")

IF XOR B

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")

IF NOT

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"))))

Nested IF simple

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:

Complex IF Table

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")

Complex IF

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:

Complex IF Helper

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:

Complex IF Grouping

Then simply press the “-“ button to hide the columns:

Complex IF Grouping

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.

IF Conditional format Table

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)

Conditional-format-NO

Conditional format Both

Here’s the result:

Conditional format 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:

IF Google Function

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 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.

Assign points based on color with the IF function

There are three things to notice in this example:

  1. The formula will return FALSE if the value in B5 is anything except «red» or «blue»
  2. The text values «red» and «blue» must be enclosed in double quotes («»)
  3. 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.

Понравилась статья? Поделить с друзьями:
  • Forms of the word get
  • Formula for excel using if
  • Formula for excel to count
  • Forms of the word fantasy
  • Formula for excel mean