If or and excel tutorial

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)

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.

Содержание

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

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.

Источник

Using IF with AND, OR and NOT functions

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

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

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

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

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

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

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

The condition you want to test.

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

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

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

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

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

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

Examples

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

Here are the formulas spelled out according to their logic:

=IF(AND(A2>0,B2 0,B4 50),TRUE,FALSE)

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

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

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

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

Here are the formulas spelled out according to their logic:

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

=IF(AND(A3>B2,A3 B2,A4 B2),TRUE,FALSE)

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

Using AND, OR and NOT with Conditional Formatting

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

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

Edit Rule dialog showing the Formula method» loading=»lazy»>

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

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

=AND(A3>B2,A3 B2,A4 B2)

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

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

Need more help?

​​​​​​​

See also

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

Источник

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.

Источник

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.

Источник

Как использовать логические функции в 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, упомянутая в этой статье. Будьте в курсе этих новых дополнений, вы будете впереди толпы.

Источник

Понравилась статья? Поделить с друзьями:
  • If only we can find the word
  • If one value is true excel
  • If one cell changes vba excel
  • If numbers between excel and
  • If number error excel