If and but formula in excel

The IF function allows you to make a logical comparison between a value and what you expect by testing for a condition and returning a result if that condition is True or False.

  • =IF(Something is True, then do something, otherwise do something else)

But what if you need to test multiple conditions, where let’s say all conditions need to be True or False (AND), or only one condition needs to be True or False (OR), or if you want to check if a condition does NOT meet your criteria? All 3 functions can be used on their own, but it’s much more common to see them paired with IF functions.

Use the IF function along with AND, OR and NOT to perform multiple evaluations if conditions are True or False.

Syntax

  • IF(AND()) — IF(AND(logical1, [logical2], …), value_if_true, [value_if_false]))

  • IF(OR()) — IF(OR(logical1, [logical2], …), value_if_true, [value_if_false]))

  • IF(NOT()) — IF(NOT(logical1), value_if_true, [value_if_false]))

Argument name

Description

logical_test (required)

The condition you want to test.

value_if_true (required)

The value that you want returned if the result of logical_test is TRUE.

value_if_false (optional)

The value that you want returned if the result of logical_test is FALSE.

Here are overviews of how to structure AND, OR and NOT functions individually. When you combine each one of them with an IF statement, they read like this:

  • AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False)

  • OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False)

  • NOT – =IF(NOT(Something is True), Value if True, Value if False)

Examples

Following are examples of some common nested IF(AND()), IF(OR()) and IF(NOT()) statements. The AND and OR functions can support up to 255 individual conditions, but it’s not good practice to use more than a few because complex, nested formulas can get very difficult to build, test and maintain. The NOT function only takes one condition.

Examples of using IF with AND, OR and NOT to evaluate numeric values and text

Here are the formulas spelled out according to their logic:

Formula

Description

=IF(AND(A2>0,B2<100),TRUE, FALSE)

IF A2 (25) is greater than 0, AND B2 (75) is less than 100, then return TRUE, otherwise return FALSE. In this case both conditions are true, so TRUE is returned.

=IF(AND(A3=»Red»,B3=»Green»),TRUE,FALSE)

If A3 (“Blue”) = “Red”, AND B3 (“Green”) equals “Green” then return TRUE, otherwise return FALSE. In this case only the first condition is true, so FALSE is returned.

=IF(OR(A4>0,B4<50),TRUE, FALSE)

IF A4 (25) is greater than 0, OR B4 (75) is less than 50, then return TRUE, otherwise return FALSE. In this case, only the first condition is TRUE, but since OR only requires one argument to be true the formula returns TRUE.

=IF(OR(A5=»Red»,B5=»Green»),TRUE,FALSE)

IF A5 (“Blue”) equals “Red”, OR B5 (“Green”) equals “Green” then return TRUE, otherwise return FALSE. In this case, the second argument is True, so the formula returns TRUE.

=IF(NOT(A6>50),TRUE,FALSE)

IF A6 (25) is NOT greater than 50, then return TRUE, otherwise return FALSE. In this case 25 is not greater than 50, so the formula returns TRUE.

=IF(NOT(A7=»Red»),TRUE,FALSE)

IF A7 (“Blue”) is NOT equal to “Red”, then return TRUE, otherwise return FALSE.

Note that all of the examples have a closing parenthesis after their respective conditions are entered. The remaining True/False arguments are then left as part of the outer IF statement. You can also substitute Text or Numeric values for the TRUE/FALSE values to be returned in the examples.

Here are some examples of using AND, OR and NOT to evaluate dates.

Examples of using IF with AND, OR and NOT to evaluate dates

Here are the formulas spelled out according to their logic:

Formula

Description

=IF(A2>B2,TRUE,FALSE)

IF A2 is greater than B2, return TRUE, otherwise return FALSE. 03/12/14 is greater than 01/01/14, so the formula returns TRUE.

=IF(AND(A3>B2,A3<C2),TRUE,FALSE)

IF A3 is greater than B2 AND A3 is less than C2, return TRUE, otherwise return FALSE. In this case both arguments are true, so the formula returns TRUE.

=IF(OR(A4>B2,A4<B2+60),TRUE,FALSE)

IF A4 is greater than B2 OR A4 is less than B2 + 60, return TRUE, otherwise return FALSE. In this case the first argument is true, but the second is false. Since OR only needs one of the arguments to be true, the formula returns TRUE. If you use the Evaluate Formula Wizard from the Formula tab you’ll see how Excel evaluates the formula.

=IF(NOT(A5>B2),TRUE,FALSE)

IF A5 is not greater than B2, then return TRUE, otherwise return FALSE. In this case, A5 is greater than B2, so the formula returns FALSE.

Example of the Evaluate Formula Wizard

Using AND, OR and NOT with Conditional Formatting

You can also use AND, OR and NOT to set Conditional Formatting criteria with the formula option. When you do this you can omit the IF function and use AND, OR and NOT on their own.

From the Home tab, click Conditional Formatting > New Rule. Next, select the “Use a formula to determine which cells to format” option, enter your formula and apply the format of your choice.

Conditional Formatting > Edit Rule dialog showing the Formula method

Using the earlier Dates example, here is what the formulas would be.

Example of using AND, OR and NOT as Conditional Formatting tests

Formula

Description

=A2>B2

If A2 is greater than B2, format the cell, otherwise do nothing.

=AND(A3>B2,A3<C2)

If A3 is greater than B2 AND A3 is less than C2, format the cell, otherwise do nothing.

=OR(A4>B2,A4<B2+60)

If A4 is greater than B2 OR A4 is less than B2 plus 60 (days), then format the cell, otherwise do nothing.

=NOT(A5>B2)

If A5 is NOT greater than B2, format the cell, otherwise do nothing. In this case A5 is greater than B2, so the result will return FALSE. If you were to change the formula to =NOT(B2>A5) it would return TRUE and the cell would be formatted.

Note: A common error is to enter your formula into Conditional Formatting without the equals sign (=). If you do this you’ll see that the Conditional Formatting dialog will add the equals sign and quotes to the formula — =»OR(A4>B2,A4<B2+60)», so you’ll need to remove the quotes before the formula will respond properly.

Need more help?

Connect with an expert. Learn from live instructors.​​​​​​​

See also

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Learn how to use nested functions in a formula

IF function

AND function

OR function

NOT function

Overview of formulas in Excel

How to avoid broken formulas

Detect errors in formulas

Keyboard shortcuts in Excel

Logical functions (reference)

Excel functions (alphabetical)

Excel functions (by category)

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:

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.

list.

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:

few conditions.

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.

two conditions.

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:

operator AND.

It’s the example of using the logical operator OR.

example of using 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):

tables.

Select the first table. Conditional Formatting — create a rule — use a formula to determine the formatted cells:

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

compare the characteristics.

Now it is easy to compare the characteristics of the data in the table.

Как использовать функцию IF

Функция IF — это основная логическая функция в Excel, и поэтому она должна быть понятна первой. Он появится много раз на протяжении всей этой статьи.

Давайте посмотрим на структуру функции IF, а затем посмотрим несколько примеров ее использования.

Функция IF принимает 3 бита информации:

  = IF (логический_тест, [value_if_true], [value_if_false]) 
  • логический_тест: это условие для функции для проверки.
  • value_if_true: действие, которое выполняется, если условие выполнено или является истинным.
  • value_if_false: действие, которое нужно выполнить, если условие не выполнено или имеет значение false.

Операторы сравнения для использования с логическими функциями

При выполнении логического теста со значениями ячеек вы должны быть знакомы с операторами сравнения. Вы можете увидеть их в таблице ниже.

Операторы сравнения для логических функций

Теперь давайте посмотрим на некоторые примеры в действии.

Пример функции IF 1: текстовые значения

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

Следующая формула используется в столбце C для отображения «Нет», если столбец B содержит текст «Завершено» и «Да», если он содержит что-либо еще.

  = ЕСЛИ (B2 = "Завершено", "Нет", "Да") 

ЕСЛИ функция для проверки текстовых значений

Хотя функция IF не чувствительна к регистру, текст должен точно соответствовать.

Пример функции IF 2: Числовые значения

Функция IF также отлично подходит для сравнения числовых значений.

В приведенной ниже формуле мы проверяем, содержит ли ячейка B2 число, большее или равное 75. Если это так, то мы отображаем слово «Pass», а если не слово «Fail».

  = ЕСЛИ (В2> = 75, "Проход", "Сбой") 

Если условие с числовыми значениями

Функция IF — это намного больше, чем просто отображение разного текста в результате теста. Мы также можем использовать его для запуска различных расчетов.

В этом примере мы хотим предоставить скидку 10%, если клиент тратит определенную сумму денег. Мы будем использовать £ 3000 в качестве примера.

  = ЕСЛИ (В2> = 3000, В2 * 90%, В2) 

Условная формула с использованием функции IF

Часть формулы B2 * 90% позволяет вычесть 10% из значения в ячейке B2. Есть много способов сделать это.

Важно то, что вы можете использовать любую формулу в разделах value_if_true или value_if_false . И запускать различные формулы, зависящие от значений других ячеек, — очень мощный навык.

Пример функции IF 3: значения даты

В этом третьем примере мы используем функцию IF для отслеживания списка сроков исполнения. Мы хотим отобразить слово «Просрочено», если дата в столбце B уже в прошлом. Но если дата наступит в будущем, рассчитайте количество дней до даты исполнения.

Приведенная ниже формула используется в столбце C. Мы проверяем, меньше ли срок оплаты в ячейке B2, чем сегодняшний день (функция TODAY возвращает сегодняшнюю дату с часов компьютера).

  = ЕСЛИ (В2 <СЕГОДНЯ (), "Просроченные", В2-СЕГОДНЯ ()) 

Тестирование, если даты должны

Что такое вложенные формулы IF?

Возможно, вы слышали о термине «вложенные IF» раньше. Это означает, что мы можем написать функцию IF внутри другой функции IF. Мы можем захотеть сделать это, если нам нужно выполнить более двух действий.

Одна функция IF способна выполнять два действия ( value_if_true и value_if_false ). Но если мы вставим (или вложим) другую функцию IF в раздел value_if_false , то мы можем выполнить другое действие.

Возьмите этот пример, где мы хотим отобразить слово «Отлично», если значение в ячейке B2 больше или равно 90, отобразить «Хорошо», если значение больше или равно 75, и отобразить «Плохо», если что-либо еще ,

  = ЕСЛИ (В2> = 90, "Отлично", ЕСЛИ (В2> = 75, "Хорошо", "Плохо")) 

Теперь мы расширили нашу формулу за пределы того, что может сделать только одна функция IF. И вы можете вложить больше функций IF, если это необходимо.

Обратите внимание на две закрывающие скобки в конце формулы — по одной для каждой функции IF.

Существуют альтернативные формулы, которые могут быть чище, чем этот вложенный подход IF. Одной из очень полезных альтернатив является функция SWITCH в Excel .

Логические функции AND и OR

Функции AND и OR используются, когда вы хотите выполнить более одного сравнения в своей формуле. Одна только функция IF может обрабатывать только одно условие или сравнение.

Возьмите пример, где мы дисконтируем значение на 10% в зависимости от суммы, которую тратит клиент, и сколько лет они были клиентом.

Сами функции AND и OR возвращают значение TRUE или FALSE.

Функция AND возвращает TRUE, только если выполняется каждое условие, а в противном случае возвращает FALSE. Функция OR возвращает TRUE, если выполняется одно или все условия, и возвращает FALSE, только если условия не выполняются.

Эти функции могут тестировать до 255 условий, поэтому они не ограничены только двумя условиями, как показано здесь.

Ниже приведена структура функций И ​​и ИЛИ. Они написаны одинаково. Просто замените имя И на ИЛИ. Это просто их логика, которая отличается.

  = И (логический1, [логический2] ...) 

Давайте посмотрим на пример того, как они оба оценивают два условия.

Пример функции AND

Функция AND используется ниже, чтобы проверить, потратил ли клиент не менее 3000 фунтов стерлингов и был ли он клиентом не менее трех лет.

  = И (В2> = 3000, С2> = 3) 

И функция в Excel

Вы можете видеть, что он возвращает FALSE для Мэтта и Терри, потому что, хотя они оба соответствуют одному из критериев, они должны соответствовать обеим функциям AND.

Пример функции OR

Функция ИЛИ используется ниже, чтобы проверить, потратил ли клиент не менее 3000 фунтов стерлингов или был клиентом не менее трех лет.

  = ИЛИ (В2> = 3000, С2> = 3) 

ИЛИ логическая функция

В этом примере формула возвращает TRUE для Matt и Terry. Только Джули и Джиллиан не выполняют оба условия и возвращают значение FALSE.

Использование AND и OR с функцией IF

Поскольку функции И и ИЛИ возвращают значение ИСТИНА или ЛОЖЬ, когда используются по отдельности, они редко используются сами по себе.

Вместо этого вы обычно будете использовать их с функцией IF или внутри функции Excel, такой как условное форматирование или проверка данных, чтобы выполнить какое-либо ретроспективное действие, если формула имеет значение TRUE.

В приведенной ниже формуле функция AND вложена в логический тест функции IF. Если функция AND возвращает TRUE, тогда скидка 10% от суммы в столбце B; в противном случае скидка не предоставляется, а значение в столбце B повторяется в столбце D.

  = ЕСЛИ (И (В2> = 3000, С2> = 3), В2 * 90%, В2) 

Формула Excel с функциями IF и AND

Функция XOR

В дополнение к функции ИЛИ, есть также эксклюзивная функция ИЛИ. Это называется функцией XOR. Функция XOR была представлена ​​в версии Excel 2013.

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

Структура функции XOR такая же, как у функции OR.

  = XOR (логический1, [логический2] ...) 

При оценке только двух условий функция XOR возвращает:

  • ИСТИНА, если любое условие оценивается как ИСТИНА.
  • FALSE, если оба условия TRUE или ни одно из условий TRUE.

Это отличается от функции ИЛИ, потому что она вернула бы ИСТИНА, если оба условия были ИСТИНА.

Эта функция становится немного более запутанной, когда добавляется больше условий. Затем функция XOR возвращает:

  • TRUE, если нечетное число условий возвращает TRUE.
  • ЛОЖЬ, если четное число условий приводит к ИСТИНА, или если все условия ЛОЖЬ.

Давайте посмотрим на простой пример функции XOR.

В этом примере продажи делятся на две половины года. Если продавец продает 3000 и более фунтов стерлингов в обеих половинах, ему назначается Золотой стандарт. Это достигается с помощью функции AND с IF, как ранее в этой статье.

Но если они продают 3000 фунтов или более в любой половине, мы хотим присвоить им Серебряный статус. Если они не продают 3000 и более фунтов стерлингов в обоих случаях, то ничего.

Функция XOR идеально подходит для этой логики. Приведенная ниже формула вводится в столбец E и показывает функцию XOR с IF для отображения «Да» или «Нет», только если выполняется любое из условий.

  = IF (XOR (В2> = 3000, С2> = 3000), "Да", "Нет") 

Функция XOR в Excel

Функция НЕ

Последняя логическая функция для обсуждения в этой статье — это функция NOT, и мы оставим самую простую последнюю. Хотя иногда поначалу бывает трудно увидеть использование этой функции в реальном мире.

Функция NOT меняет значение своего аргумента. Так что, если логическое значение ИСТИНА, тогда оно возвращает ЛОЖЬ. И если логическое значение ЛОЖЬ, оно вернет ИСТИНА.

Это будет легче объяснить на некоторых примерах.

Структура функции НЕ имеет вид;

  = НЕ (логическое) 

НЕ Функциональный Пример 1

В этом примере представьте, что у нас есть головной офис в Лондоне, а затем много других региональных сайтов. Мы хотим отобразить слово «Да», если на сайте есть что-то, кроме Лондона, и «Нет», если это Лондон.

Функция NOT была вложена в логический тест функции IF ниже, чтобы сторнировать ИСТИННЫЙ результат.

  = ЕСЛИ (НЕ (B2 = "London"), "Да", "Нет") 

не-функция-пример-1

Это также может быть достигнуто с помощью логического оператора NOT <>. Ниже приведен пример.

  = ЕСЛИ (В2 <> "Лондон", "Да", "Нет") 

НЕ Функциональный Пример 2

Функция NOT полезна при работе с информационными функциями в Excel. Это группа функций в Excel, которые что-то проверяют и возвращают TRUE, если проверка прошла успешно, и FALSE, если это не так.

Например, функция ISTEXT проверит, содержит ли ячейка текст, и вернет TRUE, если она есть, и FALSE, если нет. Функция NOT полезна, потому что она может отменить результат этих функций.

В приведенном ниже примере мы хотим заплатить продавцу 5% от суммы, которую он продает. Но если они ничего не перепродали, в ячейке есть слово «Нет», и это приведет к ошибке в формуле.

Функция ISTEXT используется для проверки наличия текста. Это возвращает TRUE, если текст есть, поэтому функция NOT переворачивает это на FALSE. И если ИФ выполняет свой расчет.

  = ЕСЛИ (НЕ (ISTEXT (В2)), В2 * 5%, 0) 

НЕ работает, пример 2

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


В этой статье рассматриваются лучшие логические функции, используемые сегодня. В последних версиях Excel появилось больше функций, добавленных в эту библиотеку, таких как функция XOR, упомянутая в этой статье. Будьте в курсе этих новых дополнений, вы будете впереди толпы.

To write an IF, AND, OR array formula in Excel 365, we must use the arithmetic operators * (multiplication) and + (addition). Why it’s so?

If we take the logical AND, OR with the IF in Excel 365 to spill the result, we won’t get our expected result.

I mean, such a formula won’t support a range/array in evaluation. Even if it supports, it won’t return an array result.

So we will replace the AND logical operator with the * (multiplication) and OR with the + (addition) arithmetic operators.

Coding the formula with the said two operators is very simple and easily readable.

I think I can convince you the same with the examples below.

Example to IF, AND, OR in Excel 365 (Non-Array Formula)

Imagine a user played a game three times, and we have recorded his scores out of 100 in cells A2, B2, and C2.

We want to perform the following three logical tests on the scores individually.

  1. If all scores are >=80, return OK.
  2. If any of the two scores are >=80, return OK.
  3. Finally, if any of the scores is >=80, return OK.

Logical Tests Using IF, AND, OR Functions

In Excel, we can perform the above three logical tests as follows.

1. E2 (If all scores are >=80, return OK)

=IF(AND(A2>=80,B2>=80,C2>=80),"OK","NOT OK")

I have used the AND function with IF in the above Excel formula to test if all the three logical tests return TRUE.

2. F2 (If any of the two scores are >=80, return OK)

We must use the following logic (two parts) to test if any two logical tests return TRUE.

AND Part:-

a) Value 1>=80 and value 2>=80.

b) Value 1>=80 and value 3>=80.

c) Value 2>=80 and value 3>=80.

OR Part:-

a) The OR evaluates to TRUE if any two of the above three AND tests return TRUE.

So the formula will be as follows.

=IF(OR(AND(A2>=80,B2>=80),AND(A2>=80,C2>=80),AND(B2>=80,C2>=80)),"OK","NOT OK")

It is an example of the IF, AND, OR logical test in Excel.

3. G2 (if any of the scores is >=80, return OK)

=IF(OR(A2>=80,B2>=80,C2>=80),"OK","NOT OK")

Here I have used the OR function with IF to test if any of the three logical tests return TRUE.

As I have already mentioned, we can’t write an IF, AND, OR array formula as above in Excel 365.

Logical Tests Using IF, *, + Formula

Let’s substitute the above three formulas by replacing AND, OR with multiplication and addition.

But that’s not enough. Then?

The below formulas are self-explanatory.

1. E2 Formula

=IF((A2:A8>=80)*(B2:B8>=80)*(C2:C8>=80),"OK","NOT OK")

How the multiplication replaces the logical function OR above?

Each test in the formula returns either TRUE or FALSE. If all the criteria are met, it will be =IF((TRUE*TRUE*TRUE),"OK","NOT OK").

We can even replace the multiplication operator here with addition.

=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>2,"OK","NOT OK")

Please remember that the value of TRUE is 1, and FALSE is 0.

2. F2 Formula

=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>1,"OK","NOT OK")

3. G2 Formula

=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>0,"OK","NOT OK")

Above I have tried to simplify the use of the logical operators within the IF function.

Now let’s open an Excel Spreadsheet and enter the scores of multiple players in the range A2:C8 as below.

IF, AND, OR Array Formula in Excel 365

So the values to evaluate are in cell range A2:C8.

I have inserted the following three IF, AND, OR array formulas in cells E2, F2, and G2, respectively.

1. E2 Array Formula

=IF((A2:A8>=80)*(B2:B8>=80)*(C2:C8>=80),"OK","NOT OK")

2. F2 Array Formula

=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>1,"OK","NOT OK")

3. G2 Array Formula

=IF((A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>0,"OK","NOT OK")

If any of the above formulas return #SPILL!, please empty the cells down in that column.

Nested IF, AND, OR Combination in Excel 365

I want to assign grades based on the scores above.

In that case, we may require to write a nested IF, AND, OR combination array formula in Excel 365.

Here is how.

In the above example, we have used three formulas for the below three logical tests.

  • If all scores are >=80, return OK.
  • If any of the two scores are >=80, return OK.
  • Finally, if any of the scores is >=80, return OK.

There each test returns OK or NOT OK.

Instead of that, here, I want the tests to return GR-1, GR-2, and GR-3.

  • If all scores are >=80, return GR-1.
  • If any of the two scores are >=80, return GR-2.
  • Finally, if any of the scores is >=80, return GR-3.

For that, we should combine the above three IF, AND, OR Array Formulas.

How?

In the E2 formula, replace “OK” with “GR-1” and “NOT OK” with the F2 formula.

In that combined (E2 and F2) formula, replace “OK” with “GR-2” and “NOT OK” with the G2 formula.

Then, in the combined E2, F2, and G2 formula, replace “OK” with “GR-3” and replace “NOT OK” with “F.”

Here it is.

Nested IF, AND, OR Combination in Excel 365

=IF(
     (A2:A8>=80)*(B2:B8>=80)*(C2:C8>=80),"GR-1",
     IF(
        (A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>1,"GR-2",
        IF(
           (A2:A8>=80)+(B2:B8>=80)+(C2:C8>=80)>0,"GR-3","F"
        )
     )
)

We can call it a nested IF, AND, OR combination array formula.

Related:- How to Use the IFS Function in Excel 365.

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

Содержание

  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

IF AND Excel Formula

The IF AND excel formula is the combination of two different logical functions often nested together that enables the user to evaluate multiple conditions using AND functions. Based on the output of the AND function, the IF function returns either the “true” or “false” value, respectively.

IF AND in Excel

  • The IF formula in ExcelIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
    read more
    is used to test and compare the conditions expressed with the expected value. It is used to test a single criterion.
  • The logical AND formula is used to test multiple criteria. It returns “true” if all the conditions mentioned are satisfied, or else returns “false.” It tests more than one criterion and accordingly returns an output. It can also be used along with the IF formula to return the desired result.
Table of contents
  • IF AND Excel Formula
    • Syntax
    • How to Use IF AND Excel Statement?
      • Example #1
      • Example #2
      • Example #3
    • The Characteristics of IF AND function
    • Frequently Asked Questions
    • Recommended Articles

Syntax

if and formula 1.2

The IF AND formula can be applied as follows:

“=IF(AND (Condition 1,Condition 2,…),Value _if _True,Value _if _False)”

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: IF AND in Excel (wallstreetmojo.com)

How to Use IF AND Excel Statement?

You can download this IF AND Formula Excel Template here – IF AND Formula Excel Template

Let us understand the usage of the IF AND formula with the help of some examples mentioned below:

Example #1

The table given below provides a list of apartments along with their age (in years) and type of society. Now we need to perform a comparative analysis for the apartments based on the age of the building and the type of society.

Here, we use the combination of less than equal (<=) to operator and the equal to (=) text functions in the condition to be demonstrated for IF AND function.

if and formula example 1.1

  • The IF AND formula used to perform the analysis is stated as follows:

      “=IF(AND(B2<=2,C2=“Gated”),“Consider”, “”)”

  • The succeeding image shows the IF AND condition applied to perform the evaluation.

if and formula example 1.3

  • Press “Enter” to get the answer.

if and formula example 1.2

  • Drag the formula to find the results for all the apartments.

if and formula example 1.4

The results in the cell D of the above table shows that the IF AND formula will be performing one among the following:

  • If both the arguments entered in the AND function is “true,” then the IF function will return that apartment to be “Consider.”
  • If either of the arguments in the AND functionThe AND function in Excel is classified as a logical function; it returns TRUE if the specified conditions are met, otherwise it returns FALSE.read more is “false” or both the arguments entered are “false,” then the IF function will return a blank string.

The IF AND formula can also perform calculations based on whether the AND function returns “true” or “false,” apart from returning only the predefined text strings.

We will understand this concept with the help of the below-mentioned example.

Example #2

The given data tableA data table in excel is a type of what-if analysis tool that allows you to compare variables and see how they impact the result and overall data. It can be found under the data tab in the what-if analysis section.read more has the list of employee name along with their orders received, performance, and salaries. Calculate the employee hike (or bonus) based on two parameters–the number of orders received and performance.

The criteria to calculate the bonus is as follows.

  • The number of orders received is greater than or equal to 200, and the performance is equal to “A.”

if and formula example 2.1

  • The IF AND formula will be,

“=IF(AND(B2>=200,C2= “A”),D2*10%,D2*5%)”

example 2.2

  • Press “Enter” to get the final output. The bonus appears in cell E2.

example 2.3 result

  • Drag the formula to find the bonus of all employees.

example 2.4

Based on these results, the IF formula does the following evaluation:

  • If both the conditions are satisfied, the AND function returns “true,” then the bonus received is calculated as salary multiplied by 10%.
  • If either one or both the conditions are found to be “false” by the AND function, then the bonus is calculated as salary multiplied by 5%.

Examples 1 and 2 have only two criteria to test and evaluate. Using multiple arguments or conditions to test them for “true” or “false” is also allowed.

Example #3

Let us evaluate multiple criteria and use AND function.

A table with five stocks and their parameter details including financial ratiosFinancial ratios are indications of a company’s financial performance. There are several forms of financial ratios that indicate the company’s results, financial risks, and operational efficiency, such as the liquidity ratio, asset turnover ratio, operating profitability ratios, business risk ratios, financial risk ratio, stability ratios, and so on.read more, such as ROCEReturn on Capital Employed (ROCE) is a metric that analyses how effectively a company uses its capital and, as a result, indicates long-term profitability. ROCE=EBIT/Capital Employed.read more, ROEReturn on Equity (ROE) represents financial performance of a company. It is calculated as the net income divided by the shareholders equity. ROE signifies the efficiency in which the company is using assets to make profit.read more, Debt to equityThe debt to equity ratio is a representation of the company’s capital structure that determines the proportion of external liabilities to the shareholders’ equity. It helps the investors determine the organization’s leverage position and risk level. read more, and PE ratioThe price to earnings (PE) ratio measures the relative value of the corporate stocks, i.e., whether it is undervalued or overvalued. It is calculated as the proportion of the current price per share to the earnings per share. read more is provided (shown in the below table).  Using this data lets us test the condition to invest in suitable stocks. That is, using the parameters, let us analyze the stocks to derive the best investment horizonThe term «investment horizon» refers to the amount of time an investor is expected to hold an investment portfolio or a security before selling it. Depending on the need for funds and risk appetite, the investor may invest for a few days or hours to a few years or decades.read more, which is important for growth.

If and in Excel example 2.5 data

The following syntax is used where the conditions are applied to arrive at the result (shown in the below table).

“=IF(AND(B2>18%,C2>20%,D2<2,E2<30%),“Invest”,“”)”

If and in Excel example 3.1 syntax

  • Press “Enter” to get the final output (Investment Criteria) of the above formula.

If and in Excel example 3.2 output

  • Drag the formula to find the Investment Criteria.

If and in Excel example 3.3

In the above data table, the AND function tests for the parameters using the operators. The resulting output generated by the IF formula is as follows:

  • If all the four criteria mentioned in the AND function are tested and satisfied, then the IF function returns the “Invest” text string.
  • If either one or more among the four conditions or all the four conditions fail to satisfy the AND function, then the IF function returns empty strings (“”).

The Characteristics of IF AND function

  • The IF AND function does not differentiate between case-insensitive texts.
  • The AND function can be used to evaluate up to 255 conditions for “true” or “false,” and the total formula length does not exceed 8192 characters.
  • Text values or blank cells are given as an argument to test the conditions in AND function.
  • The AND formula will return “#VALUE!” if there is no logical output found while evaluating the conditions.
  • IF AND excel statement is a combination of two logical functions that tests and evaluates multiple conditions.
  • The output of the AND function is based on, whether the IF function will return the value “true” or “false,” respectively.
  • IF function is used to test a single criterion whereas, the AND function is used to test multiple criteria.
  • The syntax of the IF AND formula is:

“=IF(AND (Condition 1,Condition 2,…),Value _if _True,Value _if _False)”

  • The IF AND formula also performs a calculation based on whether the AND function is “true” or “false” apart from returning only the predefined text strings.

Frequently Asked Questions

1. How to use IF AND function in Excel?

The IF AND excel statement is the two logical functions often nested together.

Syntax:
“=IF(AND(Condition1,Condition2, value_if_true,vaue_if_false)”

The IF formula is used to test and compare the conditions expressed, along with the expected value. It provides the desired result if the condition is either “true” or “false.”

The AND formula is used to test multiple criteria. It returns “true” if all the given conditions are satisfied, or else returns “false.”

2. What is the IF AND function in Excel?

IF AND formula is applied as the combination of the two logical functions that enable the user to evaluate the multiple conditions. Based on the output of the AND function, the IF function returns the output “true” or “false.”

3. How to combine IF and AND functions in Excel?

To combine IF and AND functions, you need to replace the “condition_test” argument in the IF function with AND function.

“=IF(condition_test, value_if_true,vaue_if_false)”

“=IF(AND(Condition1,Condition2, value_if_true,vaue_if_false)”

In AND function we can use multiple conditions.

Recommended Articles

This has been a guide to IF AND function in Excel. Here we discuss how to use IF Formula combined with AND function along with examples and downloadable templates. You may also look at these useful functions in Excel –

  • IF EXCEL FunctionIF function in Excel evaluates whether a given condition is met and returns a value depending on whether the result is “true” or “false”. It is a conditional function of Excel, which returns the result based on the fulfillment or non-fulfillment of the given criteria.
    read more
  • Average IF Function
  • SUMIF with Multiple CriteriaThe SUMIF (SUM+IF) with multiple criteria sums the cell values based on the conditions provided. The criteria are based on dates, numbers, and text. The SUMIF function works with a single criterion, while the SUMIFS function works with multiple criteria in excel.read more
  • Nested If ConditionIn Excel, nested if function means using another logical or conditional function with the if function to test multiple conditions. For example, if there are two conditions to be tested, we can use the logical functions AND or OR depending on the situation, or we can use the other conditional functions to test even more ifs inside a single if.read more

Excel IF AND OR functions on their own aren’t very exciting, but mix them up with the IF Statement and you’ve got yourself a formula that’s much more powerful.

In this tutorial we’re going to take a look at the basics of the AND and OR functions and then put them to work with an IF Statement.  If you aren’t familiar with IF Statements, click here to read that tutorial first.

IF Formula Builder

IF Formula Builder

Our IF Formula Builder does the hard work of creating IF formulas.

You just need to enter a few pieces of information, and the workbook creates the formula for you.

AND Function

The AND function belongs to the logic family of formulas, along with IF, OR and a few others.  It’s useful when you have multiple conditions that must be met.

In Excel language on its own the AND formula reads like this:

=AND(logical1,[logical2]....)

Now to translate into English:

=AND(is condition 1 true, AND condition 2 true (add more conditions if you want)

OR Function

The OR function is useful when you are happy if one, OR another condition is met.

In Excel language on its own the OR formula reads like this:

=OR(logical1,[logical2]....)

Now to translate into English:

=OR(is condition 1 true, OR condition 2 true (add more conditions if you want)

See, I did say they weren’t very exciting, but let’s mix them up with IF and put AND and OR to work.

IF AND Formula

First let’s set the scene of our challenge for the IF, AND formula:

In our spreadsheet below we want to calculate a bonus to pay the children’s TV personalities listed.  The rules, as devised by my 4 year old son, are:

1)      If the TV personality is Popular AND

2)      If they earn less than $100k per year they get a 10% bonus (my 4 year old will write them an IOU, he’s good for it though).

Excel IF AND OR Functions IF AND example

In cell D2 we will enter our IF AND formula as follows:

In English first

=IF(Spider Man is Popular, AND he earns <$100k),  calculate his salary x 10%, if not put "Nil" in the cell)

Now in Excel’s language:

=IF(AND(B2="Yes",C2<100),C2x$H$1,"Nil")

You’ll notice that the two conditions are typed in first, and then the outcomes are entered.  You can have more than two conditions; in fact you can have up to 30 by simply separating each condition with a comma (see warning below about going overboard with this though).

IF OR Formula

Again let’s set the scene of our challenge for the IF, OR formula:

The revised rules, as devised by my 4 year old son, are:

1)      If the TV personality is Popular OR

2)      If they earn less than $100k per year they get a 10% bonus.

IF OR Formula

In cell D2 we will enter our IF OR formula as follows:

In English first

=IF(Spider Man is Popular, OR he earns <$100k), calculate his salary x 10%, if not put “Nil” in the cell)

Now in Excel’s language:

=IF(OR(B2="Yes",C2<100),C2x$H$1,"Nil")

Notice how a subtle change from the AND function to the OR function has a significant impact on the bonus figure.

Just like the AND function, you can have up to 30 OR conditions nested in the one formula, again just separate each condition with a comma.

Try other operators

You can set your conditions to test for specific text, as I have done in this example with B2=»Yes», just put the text you want to check between inverted comas “   ”.

Alternatively you can test for a number and because the AND and OR functions belong to the logic family, you can employ different tests other than the less than (<) operator used in the examples above.

Other operators you could use are:

  • =             Equal to
  • >             Greater Than
  • <=           Less than or equal to
  • >=           Greater than or equal to
  • <>           Less than or greater than

Warning: Don’t go overboard with nesting IF, AND, and OR’s, as it will be painful to decipher if you or someone else ever needs to update the formula in months or years to come.

Note: These formulas work in all versions of Excel, however versions pre Excel 2007 are limited to 7 nested IF’s.

Download the Workbook

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.

Excel IF AND OR Practice Questions

IF AND Formula Practice

In the embedded Excel workbook below insert a formula (in the grey cells in column E), that returns the text ‘Yes’, when a product SKU should be reordered, based on the following criteria:

  1. If Stock on hand is less than 20,000 AND
  2. Demand level is ‘High’

If the above conditions are met, return ‘Yes’, otherwise, return ‘No’.

Tips for working with the embedded workbook:

  1. Use arrow keys to move around the worksheet when you can’t click on the cells with your mouse
  2. Use shortcut keys CTRL+C to copy and CTRL+V to paste
  3. Don’t forget to absolute cell references where applicable
  4. Do not enter anything in column F
  5. Double click to edit a cell
  6. Refresh the page to reset the embedded workbook

IF OR Formula Practice

In the embedded Excel workbook below insert a formula (in the grey cells in column E) that calculates the bonus due for each salesperson. A $500 bonus is paid if a salesperson meets either target in cells C24 and C25, otherwise they earn $0 bonus.

Want More Excel Formulas

Why not visit our list of Excel formulas. You’ll find a huge range all explained in plain English, plus PivotTables and other Excel tools and tricks. Enjoy 🙂

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.

Понравилась статья? Поделить с друзьями:
  • If and average functions excel
  • If all true excel
  • If all the letters of the word again
  • If column equals excel
  • If all cells are equal excel