And or symbol in excel

When you need to find data that meets more than one condition, such as units sold between April and January, or units sold by Nancy, you can use the AND and OR functions together. Here’s an example:

Using AND and OR in the same formula

This formula nests the AND function inside the OR function to search for units sold between April 1, 2011 and January 1, 2012, or any units sold by Nancy. You can see it returns
True for units sold by Nancy, and also for units sold by Tim and Ed during the dates specified in the formula.

Here’s the formula in a form you can copy and paste. If you want to play with it in a sample workbook, see the end of this article.

=OR(AND(C2>DATE(2011,4,30),C2<DATE(2012,1,1)),B2=»Nancy»)

Let’s go a bit deeper into the formula. The OR function requires a set of arguments (pieces of data) that it can test to see if they’re true or false. In this formula, the first argument is the AND function and the DATE function nested inside it, the second is «Nancy.» You can read the formula this way: Test to see if a sale was made after April 30, 2011 and before January 1, 2012, or was made by Nancy.

The AND function also returns either True or False. Most of the time, you use AND to extend the capabilities of another function, such as OR and IF. In this example, the OR function wouldn’t find the correct dates without the AND function.

Use AND and OR with IF

You can also use AND and OR with the IF function.

The AND and OR function nested in an IF function

In this example, people don’t earn bonuses until they sell at least $125,000 worth of goods, unless they work in the southern region where the market is smaller. In that case, they qualify for a bonus after $100,000 in sales.

=IF(OR(C4>=125000,AND(B4=»South»,C4>=100000))=TRUE,C4*0.12,»No bonus»)

Let’s look a bit deeper. The IF function requires three pieces of data (arguments) to run properly. The first is a logical test, the second is the value you want to see if the test returns True, and the third is the value you want to see if the test returns False. In this example, the OR function and everything nested in it provides the logical test. You can read it as: Look for values greater than or equal to 125,000, unless the value in column C is «South», then look for a value greater than 100,000, and every time both conditions are true, multiply the value by 0.12, the commission amount. Otherwise, display the words «No bonus.»

Top of Page

Sample data

If you want to work with the examples in this article, copy the following table into cell A1 in your own spreadsheet. Be sure to select the whole table, including the heading row.

Salesperson

Region

Sales

Formula/result

Miller

East

87925

=IF(OR(C2>=125000,AND(B2=»South»,C2>=100000))=TRUE,C2*0.12,»No bonus»)

Stahl

North

100000

=IF(OR(C3>=125000,AND(B3=»South»,C3>=100000))=TRUE,C3*0.12,»No bonus»)

Foster

West

145000

=IF(OR(C4>=125000,AND(B4=»South»,C4>=100000))=TRUE,C4*0.12,»No bonus»)

Wilcox

South

200750

=IF(OR(C5>=125000,AND(B5=»South»,C5>=100000))=TRUE,C5*0.12,»No bonus»)

Barnhill

South

178650

=IF(OR(C6>=125000,AND(B6=»South»,C6>=100000))=TRUE,C6*0.12,»No bonus»)

Thomas

North

99555

=IF(OR(C7>=125000,AND(B7=»South»,C7>=100000))=TRUE,C7*0.12,»No bonus»)

Keever

East

147000

=IF(OR(C8>=125000,AND(B8=»South»,C8>=100000))=TRUE,C8*0.12,»No bonus»)

Cassazza

North

213450

=IF(OR(C9>=125000,AND(B9=»South»,C9>=100000))=TRUE,C9*0.12,»No bonus»)

Brownlee

South

122680

=IF(OR(C10>=125000,AND(B10=»South»,C10>=100000))=TRUE,C10*0.12,»No bonus»)

Smithberg

West

92500

=IF(OR(C11>=125000,AND(B11=»South»,C11>=100000))=TRUE,C11*0.12,»No bonus»)

Benson

East

88350

=IF(OR(C12>=125000,AND(B12=»South»,C12>=100000))=TRUE,C12*0.12,»No bonus»)

Reading

West

102500

=IF(OR(C13>=125000,AND(B13=»South»,C13>=100000))=TRUE,C13*0.12,»No bonus»)

Top of Page

Содержание

  1. OR function
  2. Example
  3. Examples
  4. Need more help?
  5. Formula examples using the functions OR AND IF in Excel
  6. Examples of using formulas with IF, AND, OR functions in Excel
  7. Formula with logical functions AND IF OR in excel
  8. Use AND and OR to test a combination of conditions
  9. Use AND and OR with IF
  10. Sample data
  11. Как использовать логические функции в Excel: IF, AND, OR, XOR, NOT
  12. Как использовать функцию IF
  13. Операторы сравнения для использования с логическими функциями
  14. Пример функции IF 1: текстовые значения
  15. Пример функции IF 2: Числовые значения
  16. Пример функции IF 3: значения даты
  17. Что такое вложенные формулы IF?
  18. Логические функции AND и OR
  19. Пример функции AND
  20. Пример функции OR
  21. Использование AND и OR с функцией IF
  22. Функция XOR
  23. Функция НЕ
  24. НЕ Функциональный Пример 1
  25. НЕ Функциональный Пример 2

OR function

Use the OR function, one of the logical functions, to determine if any conditions in a test are TRUE.

Example

The OR function returns TRUE if any of its arguments evaluate to TRUE, and returns FALSE if all of its arguments evaluate to FALSE.

One common use for the OR function is to expand the usefulness of other functions that perform logical tests. For example, the IF function performs a logical test and then returns one value if the test evaluates to TRUE and another value if the test evaluates to FALSE. By using the OR function as the logical_test argument of the IF function, you can test many different conditions instead of just one.

The OR function syntax has the following arguments:

Required. The first condition that you want to test that can evaluate to either TRUE or FALSE.

Optional. Additional conditions that you want to test that can evaluate to either TRUE or FALSE, up to a maximum of 255 conditions.

The arguments must evaluate to logical values such as TRUE or FALSE, or in arrays or references that contain logical values.

If an array or reference argument contains text or empty cells, those values are ignored.

If the specified range contains no logical values, OR returns the #VALUE! error value.

You can use an OR array formula to see if a value occurs in an array. To enter an array formula, press CTRL+SHIFT+ENTER.

Examples

Here are some general examples of using OR by itself, and in conjunction with IF.

=OR(A2>1,A2 OR less than 100, otherwise it displays FALSE.

=IF(OR(A2>1,A2 OR less than 100, otherwise it displays the message «The value is out of range».

=IF(OR(A2 50),A2,»The value is out of range»)

Displays the value in cell A2 if it’s less than 0 OR greater than 50, otherwise it displays a message.

Sales Commission Calculation

Here is a fairly common scenario where we need to calculate if sales people qualify for a commission using IF and OR.

=IF(OR(B14>=$B$4,C14>=$B$5),B14*$B$6,0) — IF Total Sales are greater than or equal to (>=) the Sales Goal, OR Accounts are greater than or equal to (>=) the Account Goal, then multiply Total Sales by the Commission %, otherwise return 0.

Need more help?

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

Источник

Formula examples using the functions OR AND IF in Excel

Logical functions are designed to test one or several conditions, and perform the actions prescribed for each of the two possible results. Such results can only be logical TRUE or FALSE.

Excel contains several logical functions such as IF, IFERROR, SUMIF, AND, OR, and others. The last two are not used in practice, as a rule, because the result of their calculations may be one of only two possible options (TRUE, FALSE). When combined with the IF function, they are able to significantly expand its functionality.

Examples of using formulas with IF, AND, OR functions in Excel

Example 1. When calculating the cost of the amount of consumed kW of electricity for subscribers, the following conditions are taken into account:

  1. If less than 3 people live in the apartment or less than 100 kW of electricity was consumed per month, the rate per 1 kW is 4.35$.
  2. In other cases, the rate for 1 kW is 5.25$.

Calculate the amount payable per month for several subscribers.

View source data table:

Perform the calculation according to the formula:

    OR (B3 Example 2. Applicants entering the university for the specialty «mechanical engineer» are required to pass 3 exams in mathematics, physics and English. The maximum score for each exam is 100. The average passing score for 3 exams is 75, while the minimum score in physics must be at least 70 points, and in mathematics it is 80. Determine applicants who have successfully passed the exams.

View source table:

To determine the enrolled students use the formula:

  • AND(B4>=80,C4>=70,AVERAGE(B4:D4)>=75) — checked logical expressions according to the condition of the problem;
  • «Enroll» — the result, if the function AND returned the value TRUE (all expressions represented as its arguments, as a result of the calculations returned the value TRUE);
  • «Not Enroll» — the result if AND returned FALSE.

Using the autocomplete function (double-click on the cursor marker in the lower right corner), we get the rest of the results:

Formula with logical functions AND IF OR in excel

Example 3. Subsidies in the amount of 30% are charged to families with an average income below 8,000$, which are large or there is no main breadwinner. If the number of children is over 5, the amount of the subsidy is 50%. Determine who should receive subsidies and who should not.

View source table:

To check the criteria according to the condition of the problem, we write the formula:

    AND(B3 =IF( Logical_test ,[ Value_if_True ],[ Value_if_False])

As you can see, by default, you can check only one condition, for example, is e3 more than 20? Using the IF function, this check can be done as follows:

As a result, the text string “more” will be returned. If we need to find out if any value belongs to the specified interval, we will need to compare this value with the upper and lower limits of the intervals, respectively. For example, is the result of calculating e3 in the range from 20 to 25? When using the IF function alone, you must enter the following entry:

=IF(EXP(3)>20,IF(EXP(3) 20,EXP(3) 20,EXP(3) 0,EXP(3) ” means inequality, that is, more or less than some value. In this case, both expressions return the value TRUE, and the result of the execution of the IF function is the text string «true.» However, if an OR test was performed (MOD(EXP (3),1)<>0,EXP(3) 0 returns TRUE.

In practice, often used bundles IF + AND, IF + OR, or all three functions at once. Consider examples of similar use of these functions.

Источник

Use AND and OR to test a combination of conditions

When you need to find data that meets more than one condition, such as units sold between April and January, or units sold by Nancy, you can use the AND and OR functions together. Here’s an example:

This formula nests the AND function inside the OR function to search for units sold between April 1, 2011 and January 1, 2012, or any units sold by Nancy. You can see it returns True for units sold by Nancy, and also for units sold by Tim and Ed during the dates specified in the formula.

Here’s the formula in a form you can copy and paste. If you want to play with it in a sample workbook, see the end of this article.

Use AND and OR with IF

You can also use AND and OR with the IF function.

In this example, people don’t earn bonuses until they sell at least $125,000 worth of goods, unless they work in the southern region where the market is smaller. In that case, they qualify for a bonus after $100,000 in sales.

Let’s look a bit deeper. The IF function requires three pieces of data (arguments) to run properly. The first is a logical test, the second is the value you want to see if the test returns True, and the third is the value you want to see if the test returns False. In this example, the OR function and everything nested in it provides the logical test. You can read it as: Look for values greater than or equal to 125,000, unless the value in column C is «South», then look for a value greater than 100,000, and every time both conditions are true, multiply the value by 0.12, the commission amount. Otherwise, display the words «No bonus.»

Sample data

If you want to work with the examples in this article, copy the following table into cell A1 in your own spreadsheet. Be sure to select the whole table, including the heading row.

Источник

Как использовать логические функции в Excel: IF, AND, OR, XOR, NOT

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Функция XOR

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

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

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

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

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

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

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

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

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

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

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

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

Функция НЕ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

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 🙂

Once you’ve got a handle on the TRUE and FALSE functions combined with Excel’s logical operators, it’s time to learn about a couple of new functions that will allow you to combine your knowledge in totally new ways: the AND and OR functions. AND and OR do just what you would expect: check to see whether multiple conditions are true in various ways.

The AND function

The AND function checks to see whether multiple conditions are true, returning TRUE only if all logical statements within it are satisfied. The formula for the AND function is as follows:

=AND(logical_expression_1, logical_expression_2...)

You can add as many logical_expressions to the end of the function as you’d like, allowing for complex chains of logic within the function. Let’s take a look at some sample applications of AND to get a better handle on how it works:

=AND(FALSE, FALSE, FALSE)
Output: FALSE
=AND(FALSE, FALSE, TRUE)
Output: FALSE
=AND(TRUE, TRUE, TRUE)
Output: TRUE

The first and second examples above return FALSE, because not every logical_expression within them are TRUE. The third, on the other hand, returns TRUE, because every logical expression contained within the formula is TRUE.

Let’s check out AND with some actual logical statements rather than the vanilla TRUE and FALSE values:

=AND(6>3, 8<12)
Output: TRUE

The above returns TRUE, because both of the logical statements it contains are TRUE: six is greater than three, and eight is less than twelve.

Here are some more examples of the AND function in action, using more complex logical statements. Can you figure out why each of the following evaluates as such?

=AND(6<>7, 123<4)
Output: FALSE
=AND("SnackWorld"="SnackWorld", 12>=12)
Output: TRUE
=AND(6=6, 7=7, 8=8, 9=17)
Output: FALSE

The OR function

The OR function works much the same as the AND function, with one crucial difference: OR will return TRUE if one or more of the logical statements inside of it are TRUE. The formula for OR is as follows:

=OR(logical_expression_1, logical_expression_2...)

Like AND, OR can take as many logical_expressions as you want to feed it. Let’s take a look at some examples to cement our understanding of how it works:

=OR(FALSE, FALSE, FALSE)
Output: FALSE
=OR(FALSE, FALSE, TRUE)
Output: TRUE
=OR(TRUE, TRUE, TRUE)
Output: TRUE

The first example above returns FALSE because all of the statements within it are FALSE. The second and third, on the other hand, return TRUE because at least one of the statements within them are TRUE. Note the difference between this and the output for AND above.

Combining AND and OR

By now, you’re probably wondering whether it’s possible to combine AND and OR functions into a single formula. The answer is a resounding yes. You can chain AND and OR into statements as complex as you desire. When evaluating these statements, it’s helpful to go from the inside out to figure out whether they are TRUE or FALSE. Start in the innermost parentheses, which are evaluated first, and work your way outward. Here’s an example:

=AND(OR(6>3, 7<2), OR(56<>12, 78<=3))
Step 1: =AND(OR(TRUE, FALSE), OR(TRUE, FALSE)
Step 2: =AND(TRUE, TRUE)
Output: TRUE

Let’s take a look at another example of complex logic chaining:

=OR(AND(7<9, "Cookies"="Gummies"), AND(1<>2, 9<=9), AND(8=9, 10>11))
Step 1: =OR(AND(TRUE, FALSE), AND(TRUE, TRUE), AND(FALSE, FALSE))
Step 2: =OR(FALSE, TRUE, FALSE)
Output: TRUE

There you have it — now you can use the AND and OR functions to evaluate complex criteria easily!

Save an hour of work a day with these 5 advanced Excel tricks

Work smarter, not harder. Sign up for our 5-day mini-course to receive must-learn lessons on getting Excel to do your work for you.

  • How to create beautiful table formatting instantly…
  • Why to rethink the way you do VLOOKUPs
  • Plus, we’ll reveal why you shouldn’t use PivotTables and what to use instead…

Comments

Содержание

  • 1 Что возвращает функция
  • 2 Синтаксис
    • 2.1 Технические подробности
  • 3 Аргументы функции
  • 4 Совместное использование с функцией ЕСЛИ()
  • 5 Сравнение с функцией И()
  • 6 Эквивалентность функции ИЛИ() операции сложения +
  • 7 Проверка множества однотипных условий
  • 8 Примеры использования функций И ИЛИ в логических выражениях Excel
  • 9 Формула с логическим выражением для поиска истинного значения
  • 10 Формула с использованием логических функций ИЛИ И ЕСЛИ
  • 11 Особенности использования функций И, ИЛИ в Excel
  • 12 Подстановочные знаки в Excel.

Что возвращает функция

Возвращает логическое значение TRUE (Истина), при выполнении условий сравнения в функции и отображает FALSE (Ложь), если условия функции не совпадают.

Синтаксис

=OR(logical1, [logical2],…) – английская версия

=ИЛИ(логическое_значение1;[логическое значение2];…) – русская версия

Технические подробности

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

Обычно функция ИЛИ используется для расширения возможностей других функций, выполняющих логическую проверку. Например, функция ЕСЛИ выполняет логическую проверку и возвращает одно значение, если при проверке получается значение ИСТИНА, и другое значение, если при проверке получается значение ЛОЖЬ. Использование функции ИЛИ в качестве аргумента «лог_выражение» функции ЕСЛИ позволяет проверять несколько различных условий вместо одного.

Синтаксис

ИЛИ(логическое_значение1;[логическое значение2];…)

Аргументы функции ИЛИ описаны ниже.

АргументОписание

Логическое_значение1 Обязательный аргумент. Первое проверяемое условие, вычисление которого дает значение ИСТИНА или ЛОЖЬ.
Логическое_значение2;… Необязательные аргументы. Дополнительные проверяемые условия, вычисление которых дает значение ИСТИНА или ЛОЖЬ. Условий может быть не более 255.

Примечания

  • Аргументы должны принимать логические значения (ИСТИНА или ЛОЖЬ) либо быть массивами либо ссылками, содержащими логические значения.
  • Если аргумент, который является ссылкой или массивом, содержит текст или пустые ячейки, то такие значения игнорируются.
  • Если заданный диапазон не содержит логических значений, функция ИЛИ возвращает значение ошибки #ЗНАЧ!.
  • Можно воспользоваться функцией ИЛИ в качестве формулы массива, чтобы проверить, имеется ли в нем то или иное значение. Чтобы ввести формулу массива, нажмите клавиши CTRL+SHIFT+ВВОД.

Аргументы функции

  • logical1 (логическое_значение1) – первое условие которое оценивает функция по логике TRUE или FALSE;
  • [logical2] ([логическое значение2]) – (не обязательно) это второе условие которое вы можете оценить с помощью функции по логике TRUE или FALSE.

Совместное использование с функцией ЕСЛИ()

Сама по себе функция ИЛИ() имеет ограниченное использование, т.к. она может вернуть только значения ИСТИНА или ЛОЖЬ, чаще всего ее используют вместе с функцией ЕСЛИ() : =ЕСЛИ(ИЛИ(A1>100;A2>100);»Бюджет превышен»;»В рамках бюджета»)

Т.е. если хотя бы в одной ячейке (в A1 или A2 ) содержится значение больше 100, то выводится Бюджет превышен , если в обоих ячейках значения <=100, то В рамках бюджета .

Сравнение с функцией И()

Функция И() также может вернуть только значения ИСТИНА или ЛОЖЬ, но, в отличие от ИЛИ() , она возвращает ИСТИНА, только если все ее условия истинны. Чтобы сравнить эти функции составим, так называемую таблицу истинности для И() и ИЛИ() .

Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel

Эквивалентность функции ИЛИ() операции сложения +

В математических вычислениях EXCEL интерпретирует значение ЛОЖЬ как 0, а ИСТИНА как 1. В этом легко убедиться записав формулы =ИСТИНА+0 и =ЛОЖЬ+0

Следствием этого является возможность альтернативной записи формулы =ИЛИ(A1>100;A2>100) в виде =(A1>100)+(A2>100) Значение второй формулы будет =0 (ЛОЖЬ), только если оба аргумента ложны, т.е. равны 0. Только сложение 2-х нулей даст 0 (ЛОЖЬ), что совпадает с определением функции ИЛИ() .

Эквивалентность функции ИЛИ() операции сложения + часто используется в формулах с Условием ИЛИ, например, для того чтобы сложить только те значения, которые равны 5 ИЛИ равны 10: =СУММПРОИЗВ((A1:A10=5)+(A1:A10=10)*(A1:A10))

Проверка множества однотипных условий

Предположим, что необходимо сравнить некое контрольное значение (в ячейке B6 ) с тестовыми значениями из диапазона A6:A9 . Если контрольное значение совпадает хотя бы с одним из тестовых, то формула должна вернуть ИСТИНА. Можно, конечно записать формулу =ИЛИ(A6=B6;A7=B6;A8=B6;A9=B6) но существует более компактная формула, правда которую нужно ввести как формулу массива (см. файл примера ): =ИЛИ(B6=A6:A9) (для ввода формулы в ячейку вместо ENTER нужно нажать CTRL+SHIFT+ENTER )

Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel

Вместо диапазона с тестовыми значениями можно также использовать константу массива : =ИЛИ(A18:A21>{1:2:3:4})

В случае, если требуется организовать попарное сравнение списков , то можно записать следующую формулу: =ИЛИ(A18:A21>=B18:B21)

Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel

Если хотя бы одно значение из Списка 1 больше или равно (>=) соответствующего значения из Списка 2, то формула вернет ИСТИНА.

Пример 1. В учебном заведении для принятия решения о выплате студенту стипендии используют два критерия:

  1. Средний балл должен быть выше 4,0.
  2. Минимальная оценка за профильный предмет – 4 балла.

Определить студентов, которым будет начислена стипендия.

Для решения используем следующую формулу:

=И(E2>=4;СРЗНАЧ(B2:E2)>=4)

Описание аргументов:

  • E2>=4 – проверка условия «является ли оценка за профильный предмет не менее 4 баллов?»;
  • СРЗНАЧ(B2:E2)>=4 – проверка условия «является ли среднее арифметическое равным или более 4?».

Как видно выше на рисунке студенты под номером: 2, 5, 7 и 8 — не получат стипендию.

Формула с логическим выражением для поиска истинного значения

Пример 2. На предприятии начисляют премии тем работникам, которые проработали свыше 160 часов за 4 рабочих недели (задерживались на работе сверх нормы) или выходили на работу в выходные дни. Определить работников, которые будут премированы.

Исходные данные:

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

=ИЛИ(B3>160;C3=ИСТИНА())

Описание аргументов:

  • B3>160 – условие проверки количества отработанных часов;
  • C3=ИСТИНА() – условие проверки наличия часов работы в выходные дни.

Используя аналогичную формулу проведем вычисления для всех работников. Полученный результат:

То есть, оба условия возвращают значения ЛОЖЬ только в 4 случаях.

Формула с использованием логических функций ИЛИ И ЕСЛИ

Пример 3. В интернет-магазине выполнена сортировка ПК по категориям «игровой» и «офисный». Чтобы компьютер попал в категорию «игровой», он должен соответствовать следующим критериям:

  1. CPU с 4 ядрами или таковой частотой не менее 3,7 ГГц;
  2. ОЗУ – не менее 16 Гб
  3. Видеоадаптер 512-бит или с объемом памяти не менее 2 Гб

Распределить имеющиеся ПК по категориям.

Описание аргументов:

И(ИЛИ(B3>=4;C3>=3,7);D3>=16;ИЛИ(E3>=2;F3>=512)) – функция И, проверяющая 3 условия:

  1. Если число ядер CPU больше или равно 4 или тактовая частота больше или равна 3,7, результат вычисления ИЛИ(B3>=4;C3>=3,7) будет значение истинное значение;
  2. Если объем ОЗУ больше или равен 16, результат вычисления D3>=16 – ИСТИНА;
  3. Если объем памяти видеоадаптера больше или равен 2 или его разрядность больше или равна 512 – ИСТИНА.

«Игровой» — значение, если функция И возвращает истинное значение;

«Офисный» — значение, если результат вычислений И – ЛОЖЬ.

Этапы вычислений для ПК1:

  1. =ЕСЛИ(И(ИЛИ(ИСТИНА;ИСТИНА);ЛОЖЬ;ИЛИ(ЛОЖЬ;ЛОЖЬ));»Игровой»;»Офисный»)
  2. =ЕСЛИ(И(ИСТИНА;ЛОЖЬ;ЛОЖЬ);»Игровой»;»Офисный»)
  3. =ЕСЛИ(ЛОЖЬ;»Игровой»;»Офисный»)
  4. Возвращаемое значение – «Офисный»

Особенности использования функций И, ИЛИ в Excel

Функция И имеет следующую синтаксическую запись:

=И(логическое_значение1;[логическое_значение2];…)

Функция ИЛИ имеет следующую синтаксическую запись:

=ИЛИ(логическое_значение1;[логическое_значение2];…)

Описание аргументов обеих функций:

  • логическое_значение1 – обязательный аргумент, характеризующий первое проверяемое логическое условие;
  • [логическое_значение2] – необязательный второй аргумент, характеризующий второе (и последующие) условие проверки.

Примечания 1:

  1. Аргументами должны являться выражения, результатами вычислениями которых являются логические значения.
  2. Результатом вычислений функций И/ИЛИ является код ошибки #ЗНАЧ!, если в качестве аргументов были переданы выражения, не возвращающие в результате вычислений числовые значения 1, 0, а также логические ИСТИНА, ЛОЖЬ.

Примечания 2:

  1. Функция И чаще всего используется для расширения возможностей других логических функций (например, ЕСЛИ). В данном случае функция И позволяет выполнять проверку сразу нескольких условий.
  2. Функция И может быть использована в качестве формулы массива. Для проверки вектора данных на единственное условие необходимо выбрать требуемое количество пустых ячеек, ввести функцию И, в качестве аргумента передать диапазон ячеек и указать условие проверки (например, =И(A1:A10>=0)) и использовать комбинацию Ctrl+Shift+Enter. Также может быть организовано попарное сравнение (например, =И(A1:A10>B1:B10)).
  3. Как известно, логическое ИСТИНА соответствует числовому значению 1, а ЛОЖЬ – 0. Исходя из этих свойств выражения =(5>2)*(2>7) и =И(5>2;2>7) эквивалентны (Excel автоматически выполняет преобразование логических значений к числовому виду данных). Например, рассмотрим этапы вычислений при использовании данного выражения в записи =ЕСЛИ((5>2)*(2>7);”true”;”false”):
  • =ЕСЛИ((ИСТИНА)*(ЛОЖЬ);”true”;”false”);
  • =ЕСЛИ(1*0;”true”;”false”);
  • =ЕСЛИ(0;”true”;”false”);
  • =ЕСЛИ(ЛОЖЬ;”true”;”false”);
  • Возвращен результат ”false”.

Примечания 3:

  1. Функция ИЛИ чаще всего используется для расширения возможностей других функций.
  2. В отличие от функции И, функция или эквивалентна операции сложения. Например, записи =ИЛИ(10=2;5>0) и =(10=2)+(5>0) вернут значение ИСТИНА и 1 соответственно, при этом значение 1 может быть интерпретировано как логическое ИСТИНА.
  3. Подобно функции И, функция ИЛИ может быть использована как формула массива для множественной проверки условий.

Подстановочные знаки в Excel.

​ B2, поэтому формула​​ ко внешнему оператору​ функция возвращает значение​​(обязательно)​ к ней ещё​ а затем —​ помогла ли она​​ такую формулу. =СЧЁТЕСЛИ(A1:A10;B2)​​ в пустой ячейке​​ в ячейке A4,​Показать формулы​ и A3 не​
​ A1 и нажмите​ Таким образом, наша задача​, нужно сразу набрать​ будут добавлены знак​ возвращает значение ЛОЖЬ.​ ЕСЛИ. Кроме того,​ ИСТИНА.​Условие, которое нужно проверить.​
​ можно как нибудь​ клавишу ВВОД. При​ вам, с помощью​О других способах применения​ пишем такую формулу.​ возвращается «ОК», в​
Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel
​.​ равняется 24 (ЛОЖЬ).​ клавиши CTRL+V.​Во многих задачах требуется​ полностью выполнена.​ на клавиатуре знак​ равенства и кавычки:​Вы также можете использовать​ вы можете использовать​=ЕСЛИ(И(A3=»красный»;B3=»зеленый»);ИСТИНА;ЛОЖЬ)​
​значение_если_истина​​ добавить типо… Если​​ необходимости измените ширину​​ кнопок внизу страницы.​​ подстановочных знаков читайте​ Мы написали формулу​ противном случае —​Скопировав пример на пустой​=НЕ(A5=»Винты»)​
​Важно:​ проверить истинность условия​Знак​«меньше»​=»ИЛИ(A4>B2;A4. Вам потребуется удалить​ операторы И, ИЛИ​
Символ
​ текстовые или числовые​Если A3 («синий») =​(обязательно)​ A1=1 ТО A3=1​ столбцов, чтобы видеть​ Для удобства также​Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel
​ в статье «Примеры​ в ячейке В5.​​ «Неверно» (Неверно).​​ лист, его можно​​Определяет, выполняется ли следующее​​ Чтобы пример заработал должным​​ или выполнить логическое​«≠»​(, а потом элемент​ кавычки, чтобы формула​ и НЕ в​ значения вместо значений​ «красный» и B3​Значение, которое должно возвращаться,​ Ну вообщем вот​ все данные.​ приводим ссылку на​ функции «СУММЕСЛИМН» в​
Символ
​=СЧЁТЕСЛИ(A1:A10;»молок*») Как написать​=ЕСЛИ(И(A2<>A3; A2<>A4); «ОК»; «Неверно»)​ настроить в соответствии​ условие: значение в​ образом, его необходимо​Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel
​ сравнение выражений. Для​используется исключительно в​«больше»​ работала.​ формулах условного форматирования.​
​ ИСТИНА и ЛОЖЬ,​ («зеленый») равно «зеленый»,​ если лог_выражение имеет​​ это ЕСЛИ(И(A1=5;А2=5);1 и​
​Формула​ оригинал (на английском​ Excel».​ формулу с функцией​Если значение в ячейке​ с конкретными требованиями.​ ячейке A5 не​
Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel
​ вставить в ячейку​​ создания условных формул​
​ визуальных целях. Для​(>)​К началу страницы​ При этом вы​ которые возвращаются в​ возвращается значение ИСТИНА,​ значение ИСТИНА.​ вот это Если​Описание​ языке) .​Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel
​Как найти все слова​
Функция OR (ИЛИ) в Excel: как использовать? Функции ИЛИ в Excel
​ «СЧЕТЕСЛИ», читайте в​ A2 равно значению​1​
​ равняется строке «Винты»​ A1 листа.​ можно использовать функции​ формул и других​. В итоге получается​
​Если такие знаки сравнения,​ можете опустить функцию​ примерах.​ в противном случае​значение_если_ложь​
​ A1=1 ТО A3=1 ​

Источники

  • https://excelhack.ru/funkciya-or-ili-v-excel/
  • https://support.microsoft.com/ru-ru/office/%D0%B8%D0%BB%D0%B8-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D1%8F-%D0%B8%D0%BB%D0%B8-7d17ad14-8700-4281-b308-00b131e22af0
  • https://excel2.ru/articles/funkciya-ili-v-ms-excel-ili
  • https://exceltable.com/funkcii-excel/primery-logicheskih-funkciy-i-ili
  • https://my-excel.ru/excel/v-excel-znak-ili.html

excel logo

Logical functions are some of the most popular and useful in Excel. They can test values in other cells and perform actions dependent upon the result of the test. This helps us to automate tasks in our spreadsheets.

How to Use the IF Function

The IF function is the main logical function in Excel and is, therefore, the one to understand first. It will appear numerous times throughout this article.

Let’s have a look at the structure of the IF function, and then see some examples of its use.

The IF function accepts 3 bits of information:

=IF(logical_test, [value_if_true], [value_if_false])
  • logical_test: This is the condition for the function to check.
  • value_if_true: The action to perform if the condition is met, or is true.
  • value_if_false: The action to perform if the condition is not met, or is false.

Comparison Operators to Use with Logical Functions

When performing the logical test with cell values, you need to be familiar with the comparison operators. You can see a breakdown of these in the table below.

Comparison operators for logical functions

Now let’s look at some examples of it in action.

IF Function Example 1: Text Values

In this example, we want to test if a cell is equal to a specific phrase. The IF function is not case-sensitive so does not take upper and lower case letters into account.

The following formula is used in column C to display “No” if column B contains the text “Completed” and “Yes” if it contains anything else.

=IF(B2="Completed","No","Yes")

IF function to test text values

Although the IF function is not case sensitive, the text must be an exact match.

IF Function Example 2: Numeric Values

The IF function is also great for comparing numeric values.

In the formula below we test if cell B2 contains a number greater than or equal to 75. If it does, then we display the word “Pass,” and if not the word “Fail.”

=IF(B2>=75,"Pass","Fail")

If condition with numeric values

The IF function is a lot more than just displaying different text on the result of a test. We can also use it to run different calculations.

In this example, we want to give a 10% discount if the customer spends a certain amount of money. We will use £3,000 as an example.

=IF(B2>=3000,B2*90%,B2)

Conditional formula by using the IF function

The B2*90% part of the formula is a way that you can subtract 10% from the value in cell B2. There are many ways of doing this.

What’s important is that you can use any formula in the value_if_true or value_if_false sections. And running different formulas dependent upon the values of other cells is a very powerful skill to have.

IF Function Example 3: Date Values

In this third example, we use the IF function to track a list of due dates. We want to display the word “Overdue” if the date in column B is in the past. But if the date is in the future, calculate the number of days until the due date.

The formula below is used in column C. We check if the due date in cell B2 is less than today’s date (The TODAY function returns today’s date from the computer’s clock).

=IF(B2<TODAY(),"Overdue",B2-TODAY())

Testing if dates are due

What are Nested IF Formulas?

You may have heard of the term nested IFs before. This means that we can write an IF function within another IF function. We may want to do this if we have more than two actions to perform.

One IF function is capable of performing two actions (the value_if_true and value_if_false ). But if we embed (or nest) another IF function in the value_if_false section, then we can perform another action.

Take this example where we want to display the word “Excellent” if the value in cell B2 is greater than or equal to 90, display “Good” if the value is greater than or equal to 75, and display “Poor” if anything else.

=IF(B2>=90,"Excellent",IF(B2>=75,"Good","Poor"))

We have now extended our formula to beyond what just one IF function can do. And you can nest more IF functions if necessary.

Notice the two closing brackets on the end of the formula—one for each IF function.

There are alternative formulas that can be cleaner than this nested IF approach. One very useful alternative is the SWITCH function in Excel.

The AND and OR functions are used when you want to perform more than one comparison in your formula. The IF function alone can only handle one condition, or comparison.

Take an example where we discount a value by 10% dependent upon the amount a customer spends and how many years they have been a customer.

On their own, the AND and OR functions will return the value of TRUE or FALSE.

The AND function returns TRUE only if every condition is met, and otherwise returns FALSE. The OR function returns TRUE if one or all of the conditions are met, and returns FALSE only if no conditions are met.

These functions can test up to 255 conditions, so are certainly not limited to just two conditions like is demonstrated here.

Below is the structure of the AND and OR functions. They are written the same. Just substitute the name AND for OR. It is just their logic which is different.

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

Let’s see an example of both of them evaluating two conditions.

AND Function example

The AND function is used below to test if the customer spends at least £3,000 and has been a customer for at least three years.

=AND(B2>=3000,C2>=3)

AND function in Excel

You can see that it returns FALSE for Matt and Terry because although they both meet one of the criteria, they need to meet both with the AND function.

OR Function Example

The OR function is used below to test if the customer spends at least £3,000 or has been a customer for at least three years.

=OR(B2>=3000,C2>=3)

The OR logical function

In this example, the formula returns TRUE for Matt and Terry. Only Julie and Gillian fail both conditions and return the value of FALSE.

Using AND and OR with the IF Function

Because the AND and OR functions return the value of TRUE or FALSE when used alone, it’s rare to use them by themselves.

Instead, you’ll typically use them with the IF function, or within an Excel feature such as Conditional Formatting or Data Validation to perform some retrospective action if the formula evaluates to TRUE.

In the formula below, the AND function is nested inside the IF function’s logical test. If the AND function returns TRUE then 10% is discounted from the amount in column B; otherwise, no discount is given and the value in column B is repeated in column D.

=IF(AND(B2>=3000,C2>=3),B2*90%,B2)

Excel formula with IF and AND functions

The XOR Function

In addition to the OR function, there is also an exclusive OR function. This is called the XOR function. The XOR function was introduced with the Excel 2013 version.

This function can take some effort to understand, so a practical example is shown.

The structure of the XOR function is the same as the OR function.

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

When evaluating just two conditions the XOR function returns:

  • TRUE if either condition evaluates to TRUE.
  • FALSE if both conditions are TRUE, or neither condition is TRUE.

This differs from the OR function because that would return TRUE if both conditions were TRUE.

This function gets a little more confusing when more conditions are added. Then the XOR function returns:

  • TRUE if an odd number of conditions return TRUE.
  • FALSE if an even number of conditions result in TRUE, or if all conditions are FALSE.

Let’s look at a simple example of the XOR function.

In this example, sales are split over two halves of the year. If a salesperson sells £3,000 or more in both halves then they are assigned Gold standard. This is achieved with an AND function with IF like earlier in the article.

But if they sell £3,000 or more in either half then we want to assign them Silver status. If they don’t sell £3,000 or more in both then nothing.

The XOR function is perfect for this logic. The formula below is entered into column E and shows the XOR function with IF to display  “Yes” or “No” only if either condition is met.

=IF(XOR(B2>=3000,C2>=3000),"Yes","No")

The XOR Function in Excel

The NOT Function

The final logical function to discuss in this article is the NOT function, and we have left the simplest for last. Although sometimes it can be hard to see the ‘real world’ uses of the function at first.

The NOT function reverses the value of its argument. So if the logical value is TRUE, then it returns FALSE. And if the logical value is FALSE, it will return TRUE.

This will be easier to explain with some examples.

The structure of the NOT function is;

=NOT(logical)

NOT Function Example 1

In this example, imagine we have a head office in London and then many other regional sites. We want to display the word “Yes” if the site is anything except London, and “No” if it is London.

The NOT function has been nested in the logical test of the IF function below to reverse the TRUE result.

=IF(NOT(B2="London"),"Yes","No")

This can also be achieved by using the NOT logical operator of <>. Below is an example.

=IF(B2<>"London","Yes","No")

NOT Function Example 2

The NOT function is useful when working with information functions in Excel. These are a group of functions in Excel that check something, and return TRUE if the check is a success, and FALSE if it is not.

For example, the ISTEXT function will check if a cell contains text and return TRUE if it does and FALSE if it does not. The NOT function is helpful because it can reverse the result of these functions.

In the example below, we want to pay a salesperson 5% of the amount they upsell. But if they did not upsell anything, the word “None” is in the cell and this will produce an error in the formula.

The ISTEXT function is used to check for the presence of text. This returns TRUE if there is text, so the NOT function reverses this to FALSE. And the IF performs its calculation.

=IF(NOT(ISTEXT(B2)),B2*5%,0)

NOT function example 2

Mastering logical functions will give you a big advantage as an Excel user. To be able to test and compare values in cells and perform different actions based on those results is very useful.


This article has covered the best logical functions used today. Recent versions of Excel have seen the introduction of more functions added to this library, such as the XOR function mentioned in this article. Keeping up to date with these new additions will keep you ahead of the crowd.

READ NEXT

  • › How to Use an Advanced Filter in Microsoft Excel
  • › Functions vs. Formulas in Microsoft Excel: What’s the Difference?
  • › 13 Essential Excel Functions for Data Entry
  • › How to Group Worksheets in Excel
  • › How to Count Characters in Microsoft Excel
  • › How to Find the Function You Need in Microsoft Excel
  • › How to Use the IS Functions in Microsoft Excel
  • › BLUETTI Slashed Hundreds off Its Best Power Stations for Easter Sale

Logical functions are designed to test one or several conditions, and perform the actions prescribed for each of the two possible results. Such results can only be logical TRUE or FALSE.

Excel contains several logical functions such as IF, IFERROR, SUMIF, AND, OR, and others. The last two are not used in practice, as a rule, because the result of their calculations may be one of only two possible options (TRUE, FALSE). When combined with the IF function, they are able to significantly expand its functionality.



Examples of using formulas with IF, AND, OR functions in Excel

Example 1. When calculating the cost of the amount of consumed kW of electricity for subscribers, the following conditions are taken into account:

  1. If less than 3 people live in the apartment or less than 100 kW of electricity was consumed per month, the rate per 1 kW is 4.35$.
  2. In other cases, the rate for 1 kW is 5.25$.

Calculate the amount payable per month for several subscribers.

View source data table:

Example 1.

Perform the calculation according to the formula:

Argument Description:

  • OR (B3<=2,C3<100) is a logical expression that verifies two conditions: do less than 3 people live in the apartment or does the total amount of energy consumed less than 100 kW? The result of the test will be TRUE if either of these two conditions is true;
  • C3 * 4.35 — the amount to be paid, if the OR function returns TRUE;
  • C3 * 5.25 is the amount to be paid if OR returns FALSE.

We stretch the formula for the remaining cells using the autocomplete function. The result of the calculation for each subscriber:

several logical functions.

Using the AND function in the formula in the first argument in the IF function, we check the conformity of the values by two conditions at once.



Formula with IF and AVERAGE functions for selecting of values by conditions

Example 2. Applicants entering the university for the specialty «mechanical engineer» are required to pass 3 exams in mathematics, physics and English. The maximum score for each exam is 100. The average passing score for 3 exams is 75, while the minimum score in physics must be at least 70 points, and in mathematics it is 80. Determine applicants who have successfully passed the exams.

View source table:

Example 2.

To determine the enrolled students use the formula:

Argument Description:

  • AND(B4>=80,C4>=70,AVERAGE(B4:D4)>=75) — checked logical expressions according to the condition of the problem;
  • «Enroll» — the result, if the function AND returned the value TRUE (all expressions represented as its arguments, as a result of the calculations returned the value TRUE);
  • «Not Enroll» — the result if AND returned FALSE.

Using the autocomplete function (double-click on the cursor marker in the lower right corner), we get the rest of the results:

Formula with IF and AVERAGE.

Formula with logical functions AND IF OR in excel

Example 3. Subsidies in the amount of 30% are charged to families with an average income below 8,000$, which are large or there is no main breadwinner. If the number of children is over 5, the amount of the subsidy is 50%. Determine who should receive subsidies and who should not.

View source table:

Example 3.

To check the criteria according to the condition of the problem, we write the formula:

Argument Description:

  • AND(B3<8000,OR(C3=TRUE,E3=FALSE)) is the checked expression according to the condition of the problem. In this case, the AND function returns the TRUE value, if B3 <8000 is true and at least one of the expressions passed as arguments to the OR function also returns the TRUE value.
  • The nested IF function performs a check on the number of children in the family, which rely on subsidies.
  • If the main condition returned the result is FALSE, the main function IF returns the text string “no”.

Perform the calculation for the first family and stretch the formula to the remaining cells using the autocomplete function. Results:

functions AND IF OR.

Features of using logical functions IF, AND, OR in Excel

The IF function has the following syntax notation:

=IF(Logical_test,[ Value_if_True ],[ Value_if_False])

As you can see, by default, you can check only one condition, for example, is e3 more than 20? Using the IF function, this check can be done as follows:

=IF(EXP(3)>20,»more»,»less»)

As a result, the text string “more” will be returned. If we need to find out if any value belongs to the specified interval, we will need to compare this value with the upper and lower limits of the intervals, respectively. For example, is the result of calculating e3 in the range from 20 to 25? When using the IF function alone, you must enter the following entry:

=IF(EXP(3)>20,IF(EXP(3)<25,»belongs»,»does not belong»),»does not belong»)

We have a nested function IF as one of the possible results of the implementation of the main function IF, and therefore the syntax looks somewhat cumbersome. If you also need to know, for example, whether the square root e3 is equal to a numeric value from a fractional number range from 4 to 5, the final formula will look cumbersome and unreadable.

It is much easier to use as a condition a complex expression that can be written using AND and OR functions. For example, the above function can be rewritten as follows:

=IF(AND(EXP(3)>20,EXP(3)<25),»belongs»,»does not belong»)

The result of the execution of the AND expression (EXP(3)>20,EXP(3)<25) can be a logical value TRUE only if the result of checking each of the specified conditions is a logical value TRUE. In other words, the function AND allows you to test one, two or more hypotheses on their truth, and returns the result FALSE if at least one of them is incorrect.

Sometimes you want to know if at least one assumption is true. In this case, it is convenient to use the OR function, which performs the check of one or several logical expressions and returns a logical TRUE, if the result of the calculations of at least one of them is a logical TRUE. For example, you want to know if e3 is an integer or a number that is less than 100? To test this condition, you can use the following formula:

=IF(OR(MOD(EXP(3),1)<>0,EXP(3)<100),»true»,»false»)

The “<>” means inequality, that is, more or less than some value. In this case, both expressions return the value TRUE, and the result of the execution of the IF function is the text string «true.» However, if an OR test was performed (MOD(EXP (3),1)<>0,EXP(3)<20, while EXP(3) <20 will return FALSE, the result of the calculation of the IF function will not change, since MOD(EXP(3),1) <> 0 returns TRUE.

Download examples using the functions OR AND IF in Excel

In practice, often used bundles IF + AND, IF + OR, or all three functions at once. Consider examples of similar use of these functions.

Понравилась статья? Поделить с друзьями:
  • And or not syntax excel
  • And or not operators in excel
  • And or in if statement vba excel
  • And or advanced filter excel
  • And operator with if in excel