Excel if with or clause

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)

Содержание

  1. IF function
  2. Simple IF examples
  3. Common problems
  4. Need more help?
  5. Use AND and OR to test a combination of conditions
  6. Use AND and OR with IF
  7. Sample data
  8. OR function
  9. Example
  10. Examples
  11. Need more help?
  12. Create conditional formulas
  13. What do you want to do?
  14. Create a conditional formula that results in a logical value (TRUE or FALSE)
  15. Example
  16. Create a conditional formula that results in another calculation or in values other than TRUE or FALSE
  17. Example
  18. Formula examples using the functions OR AND IF in Excel
  19. Examples of using formulas with IF, AND, OR functions in Excel
  20. Formula with logical functions AND IF OR in excel

IF function

The IF function is one of the most popular functions in Excel, and it allows you to make logical comparisons between a value and what you expect.

So an IF statement can have two results. The first result is if your comparison is True, the second if your comparison is False.

For example, =IF(C2=”Yes”,1,2) says IF(C2 = Yes, then return a 1, otherwise return a 2).

Use the IF function, one of the logical functions, to return one value if a condition is true and another value if it’s false.

IF(logical_test, value_if_true, [value_if_false])

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.

Simple IF examples

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

In this example, the formula in cell D2 says: IF(C2 = 1, then return Yes, otherwise return No)As you see, the IF function can be used to evaluate both text and values. It can also be used to evaluate errors. You are not limited to only checking if one thing is equal to another and returning a single result, you can also use mathematical operators and perform additional calculations depending on your criteria. You can also nest multiple IF functions together in order to perform multiple comparisons.

B2,”Over Budget”,”Within Budget”)» loading=»lazy»>

=IF(C2>B2,”Over Budget”,”Within Budget”)

In the above example, the IF function in D2 is saying IF(C2 Is Greater Than B2, then return “Over Budget”, otherwise return “Within Budget”)

B2,C2-B2,»»)» loading=»lazy»>

In the above illustration, instead of returning a text result, we are going to return a mathematical calculation. So the formula in E2 is saying IF(Actual is Greater than Budgeted, then Subtract the Budgeted amount from the Actual amount, otherwise return nothing).

In this example, the formula in F7 is saying IF(E7 = “Yes”, then calculate the Total Amount in F5 * 8.25%, otherwise no Sales Tax is due so return 0)

Note: If you are going to use text in formulas, you need to wrap the text in quotes (e.g. “Text”). The only exception to that is using TRUE or FALSE, which Excel automatically understands.

Common problems

What went wrong

There was no argument for either value_if_true or value_if_False arguments. To see the right value returned, add argument text to the two arguments, or add TRUE or FALSE to the argument.

This usually means that the formula is misspelled.

Need more help?

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

Источник

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.

Источник

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.

Источник

Create conditional formulas

Testing whether conditions are true or false and making logical comparisons between expressions are common to many tasks. You can use the AND, OR, NOT, and IF functions to create conditional formulas.

For example, the IF function uses the following arguments.

Formula that uses the IF function

logical_test: The condition that you want to check.

value_if_true: The value to return if the condition is True.

value_if_false: The value to return if the condition is False.

For more information about how to create formulas, see Create or delete a formula.

What do you want to do?

Create a conditional formula that results in a logical value (TRUE or FALSE)

To do this task, use the AND, OR, and NOT functions and operators as shown in the following example.

Example

The example may be easier to understand if you copy it to a blank worksheet.

How do I copy an example?

Select the example in this article.

Selecting an example from Help

In Excel, create a blank workbook or worksheet.

In the worksheet, select cell A1, and press CTRL+V.

Important: For the example to work properly, you must paste it into cell A1 of the worksheet.

To switch between viewing the results and viewing the formulas that return the results, press CTRL+` (grave accent), or on the Formulas tab, in the Formula Auditing group, click the Show Formulas button.

After you copy the example to a blank worksheet, you can adapt it to suit your needs.

Determines if the value in cell A2 is greater than the value in A3 and also if the value in A2 is less than the value in A4. (FALSE)

Determines if the value in cell A2 is greater than the value in A3 or if the value in A2 is less than the value in A4. (TRUE)

Determines if the sum of the values in cells A2 and A3 is not equal to 24. (FALSE)

Determines if the value in cell A5 is not equal to «Sprockets.» (FALSE)

Determines if the value in cell A5 is not equal to «Sprockets» or if the value in A6 is equal to «Widgets.» (TRUE)

For more information about how to use these functions, see AND function, OR function, and NOT function.

Create a conditional formula that results in another calculation or in values other than TRUE or FALSE

To do this task, use the IF, AND, and OR functions and operators as shown in the following example.

Example

The example may be easier to understand if you copy it to a blank worksheet.

How do I copy an example?

Select the example in this article.

Important: Do not select the row or column headers.

Selecting an example from Help

In Excel, create a blank workbook or worksheet.

In the worksheet, select cell A1, and press CTRL+V.

Important: For the example to work properly, you must paste it into cell A1 of the worksheet.

To switch between viewing the results and viewing the formulas that return the results, press CTRL+` (grave accent), or on the Formulas tab, in the Formula Auditing group, click the Show Formulas button.

After you copy the example to a blank worksheet, you can adapt it to suit your needs.

=IF(A2=15, «OK», «Not OK»)

If the value in cell A2 equals 15, return «OK.» Otherwise, return «Not OK.» (OK)

=IF(A2<>15, «OK», «Not OK»)

If the value in cell A2 is not equal to 15, return «OK.» Otherwise, return «Not OK.» (Not OK)

=IF(NOT(A2 «SPROCKETS», «OK», «Not OK»)

If the value in cell A5 is not equal to «SPROCKETS», return «OK.» Otherwise, return «Not OK.» (Not OK)

If the value in cell A2 is greater than the value in A3 and the value in A2 is also less than the value in A4, return «OK.» Otherwise, return «Not OK.» (Not OK)

=IF(AND(A2<>A3, A2<>A4), «OK», «Not OK»)

If the value in cell A2 is not equal to A3 and the value in A2 is also not equal to the value in A4, return «OK.» Otherwise, return «Not OK.» (OK)

If the value in cell A2 is greater than the value in A3 or the value in A2 is less than the value in A4, return «OK.» Otherwise, return «Not OK.» (OK)

=IF(OR(A5<>«Sprockets», A6<>«Widgets»), «OK», «Not OK»)

If the value in cell A5 is not equal to «Sprockets» or the value in A6 is not equal to «Widgets», return «OK.» Otherwise, return «Not OK.» (Not OK)

=IF(OR(A2<>A3, A2<>A4), «OK», «Not OK»)

If the value in cell A2 is not equal to the value in A3 or the value in A2 is not equal to the value in A4, return «OK.» Otherwise, return «Not OK.» (OK)

For more information about how to use these functions, see IF function, AND function, and OR function.

Источник

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.

Источник

A fruit seller is selling apples. You will buy apples only if they are Red or Juicy. If an apple is not Red nor Juicy, you will not buy it.
34
Here we have two conditions and at least one of them need to be true to make you happy. Let’s write an IF OR formula for this in Excel 2016.
Implementation of IF with OR
Generic Formula

=IF(OR(condition1, condition2,…),value if true, value if false)

Example
Let’s consider the example we discussed in the beginning.
We have this table of apple’s colour and type.
If the colour is “Red” or type is “Juicy” then write OK in column D. If the color is not “Red”, nor the type is “Juicy” then type Not OK.
35
Write this IF OR formula in D2 column and drag it down.

=IF(OR(B3=»Red»,C3=»Juicy»),»OK»,»Not OK»)

And you can see now that only apples that are Red or Juicy are marked OK.
36
How It Works
IF Statement : You know how IF function in Excel works. It takes a boolean expression as first argument and returns one expression if TRUE and another if FALSE. Learn more about The Excel  IF function.

=IF(TRUE or FALSE, statement if True, statement if false)

OR Function: Checks multiple conditions. Returns TRUE only if at least one of the conditions is TRUE else returns FALSE.

=OR(condition1, condition2,….) ==> TRUE/FALSE

In the end, OR function provides IF function TRUE or FALSE argument and based on that IF prints the result.
Alternate Solution:
Another way to do this is to use nested IFs for Multiple Conditions.

=IF(B3=»Red», “OK”, IF(C3=»Juicy»,”OK”,”Not OK”),”Not OK”)

Nested IF is good when we want different results but not when only one result. It will work but for multiple conditions, it will make your excel formula too long.

So here we learned about how to use IF with OR to check multiple conditions and show results if at least one of all conditions is TRUE. But what if you want to show results only if all condition is true. We will use AND function with IF in excel to do so.

Related Articles:

Excel OR function

Excel AND Function

IF with AND Function in Excel

Excel TRUE Function

Excel NOT function

IF not this or that in Microsoft Excel

IF with AND and OR function in Excel

Popular Articles:

The VLOOKUP Function in Excel

COUNTIF in Excel 2016

How to Use SUMIF Function in Excel

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 🙂

To perform complicated and powerful data analysis, you need to test various conditions at a single point in time. The data analysis might require logical tests also within these multiple conditions.

For this, you need to perform Excel if statement with multiple conditions or ranges that include various If functions in a single formula.

Those who use Excel daily are well versed with Excel If statement as it is one of the most-used formula. Here you can check various Excel If or statement, Nested If, AND function, Excel IF statements, and how to use them. We have also provided a VIDEO TUTORIAL for different If Statements.

There are various If statements available in Excel. You have to know which of the Excel If you will work at what condition. Here you can check multiple conditions where you can use Excel If statement.

1) Excel If Statement

Excel-If-functions

If you want to test a condition to get two outcomes then you can use this Excel If statement.

=If(Marks>=40, “Pass”)

2) Nested If Statement

Let’s take an example that met the below-mentioned condition

  • If the score is between 0 to 60, then Grade F
  • If the score is between 61 to 70, then Grade D
  • If the score is between 71 to 80, then Grade C
  • If the score is between 81 to 90, then Grade B
  • If the score is between 91 to 100, then Grade A

Then to test the condition the syntax of the formula becomes,

=If(B5<60, “F”,If(B5<71, “D”, If(B5<81,”C”,If(B5<91,”B”,”A”)

Nested-If-statement

3) Excel If with Logical Test

There are 2 different types of conditions AND and OR. You can use the IF statement in excel between two values in both these conditions to perform the logical test.

AND Function: If you are performing the logical test based on AND function, then excel will give you TRUE as an outcome in every condition else it will return false.

OR Function: If you are using OR condition for the logical test, then excel will give you an outcome as TRUE if any of the situations match else it returns false.

For this, multiple testing is to be done using AND and OR function, you should gain expertise in using either or both of these with IF statement. Here we have used if the function with 3 conditions.

How to apply IF & AND function in Excel

  • To perform this multiple if and statements in excel, we will take the data set for the student’s marks that contain fields such as English and Math’s Marks.
  • The score of the English subject is stored in the D column whereas the Maths score is stored in column E.
  • Let say a student passes the class if his or her score in English is greater than or equal to 20 and he or she scores more than 60 in Maths.
  • To create a report in matters of seconds, if formula combined with AND can suffice.
  • Type =IF( Excel will display the logical hint just below the cell F2. The parameters of this function are logical_test, value_if_true, value_if_false.
  • The first parameter contains the condition to be matched. You can use multiple If and AND conditions combined in this logical test.
  • In the second parameter, type the value that you want Excel to display if the condition is true. Similarly, in the third parameter type the value that will be displayed if your condition is false.Excel-if-statement-multiple-condition-range
  • Apply If & And formula, you will get =IF(AND(D2>=20,E2>=60),”Pass”,”Fail”).

If formula

  • Add Pass/Fail column in the current table.Excel-If-conditions
  • After you have applied this formula, you will find the result in the column.
  • Copy the formula from cell F2 and paste in all other cells from F3 to F13.Excel-If-And-statement

How to use If with Or function in Excel

To use If and Or statement excel, you need to apply a similar formula as you have applied for If & And with the only difference is that if any of the condition is true then it will show you True.

To apply the formula, you have to follow the above process. The formula is =IF((OR(D2>=20, E2>=60)), “Pass”, “Fail”). If the score is equal or greater than 20 for column D or the second score is equal or greater than 60 then the person is the pass.

How to Use If with And & Or function

If you want to test data based on several multiple conditions then you have to apply both And & Or functions at a single point in time. For example,

Situation 1: If column D>=20 and column E>=60

Situation 2: If column D>=15 and column E>=60

If any of the situations met, then the candidate is passed, else failed. The formula is

=IF(OR(AND(D2>=20, E2>=60), AND(D2>=20, E2>=60)), “Pass”, “Fail”).

4) Excel If Statement with other functions

Above we have learned how to use excel if statement multiple conditions range with And/Or functions. Now we will be going to learn Excel If Statement with other excel functions.

  • Excel If with Sum, Average, Min, and Max functions

Let’s take an example where we want to calculate the performance of any student with Poor, Satisfactory, and Good.

If the data set has a predefined structure that will not allow any of the modifications. Then you can add values with this If formula:

=If((A2+B2)>=50, “Good”, If((A2+B2)=>30, “Satisfactory”, “Poor”))

Using the Sum function,

=If(Sum(A2:B2)>=120, “Good”, If(Sum(A2:B2)>=100, “Satisfactory”, “Poor”))

Using the Average function,

=If(Average(A2:B2)>=40, “Good”, If(Average(A2:B2)>=25, “Satisfactory”, “Poor”))

Using Max/Min,

If you want to find out the highest scores, using the Max function. You can also find the lowest scores using the Min function.

=If(C2=Max($C$2:$C$10), “Best result”, “ “)

You can also find the lowest scores using the Min function.

=If(C2=Min($C$2:$C$10), “Worst result”, “ “)

If we combine both these formulas together, then we get

=If(C2=Max($C$2:$C$10), “Best result”, If(C2=Min($C$2:$C$10), “Worst result”, “ “))

You can also call it as nested if functions with other excel functions. To get a result, you can use these if functions with various different functions that are used in excel.

So there are four different ways and types of excel if statements, that you can use according to the situation or condition. Start using it today.

So this is all about Excel If statement multiple conditions ranges, you can also check how to add bullets in excel in our next post.

I hope you found this tutorial useful

You may also like the following Excel tutorials:

  • Multiple If Statements in Excel
  • Excel Logical test
  • How to Compare Two Columns in Excel (using VLOOKUP & IF)
  • Using IF Function with Dates in Excel (Easy Examples)

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.

Home / Excel Formulas / How to Combine IF and OR Functions in Excel

IF Function is one of the most powerful functions in excel. And, the best part is, that you can combine other functions with IF to increase its power.

Combining IF and OR functions is one of the most useful formula combinations in excel. In this post, I’ll show you why we need to combine IF and OR functions. And, why it’s highly useful for you.

Quick Intro

I am sure you have used both of these functions but let me give you a quick intro.

  • IF – Use this function to test a condition. It will return a specific value if that condition is true, or else some other specific value if that condition is false.
  • OR – Test multiple conditions. It will return true if any of those conditions is true, and false if all of those conditions are false.

The crux of both of the functions is IF function can test only one condition at a time. And, OR function can test multiple conditions but only return true/false. And, if we combine these two functions we can test multiple conditions with OR & return a specific value with IF.

How do IF and OR functions Work?

In the syntax of the IF function, have a logical test argument that we use to specify a condition to test.

IF(logical_test,value_if_true,value_if_false)

And, then it returns a value based on the result of that condition. Now, if we use OR function for that argument and specify multiple conditions for it.

how to combine if and or functions and replace logical argument with or

If any of the conditions is true OR will return true and IF will return the specific value. And, if none of the conditions is true OR with return FALSE IF will return another specific value. In this way, we can test more than one value with the IF function. Let’s get into some real-life examples.

Examples

Here I have a table with stock details of two warehouses. Now the thing is I want to update the status in the table.

how to combine if and or functions to get status in stock table

If there is no stock in both of the warehouses status should be “Out of Stock”. And, if there is stock in any of the warehouse status should be “In-Stocks”. So here I have to check two different conditions “Warehouse-1” & “Warehouse-2”.
And the formula will be.

=IF(OR(B2>0,C2>0),"In-Stock","Out of Stock")
how to combine if and or functions to get status in stock table insert formula

In the above formula, if there is a value greater than zero in any of the cells (B2 & C2) OR function will return true, and IF will return the value “In-Stock”. But, if both cells have zero then OR will return false, and IF will return the value “Out of Stock”.

Download Sample File

  • Ready

Last Words

Both of the functions are equally useful but when you combine them, you can use them in a better way. As I told you, by combining IF and Or functions you can test more than one condition. You can solve your two problems with this combination of functions.

And, if you want to Get Smarter than Your Colleagues check out these FREE COURSES to Learn Excel, Excel Skills, and Excel Tips and Tricks.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

И функция в Excel

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

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

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

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

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

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

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

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

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

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

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

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

Функция XOR

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Функция XOR в Excel

Функция НЕ

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

Date yes Add (Subtract) Days to a Date Concatenate Dates Convert Date to Number Convert Date to Text Month Name to Number Create Date Range from Dates Day Number of Year Month Name from Date First Day of Month Add (Subtract) Weeks to a Date If Functions with Dates Max Date Number of Days Between Dates Number of Days in a Month Number of Weeks Between Dates Number of Years Between Dates Split Date & Time into Separate Cells Countdown Remaining Days Insert Dates Random Date Generator Using Dynamic Ranges — Year to Date Values Add (Subtract) Years to a Date Date Formula Examples Extract Day from Date Get Day Name from Date Count Days Left in Month / Year Count Workdays Left in Month / Year Get Last Day of Month Last Business Day of Month / Year Number of Work / Business Days in Month Weekday Abbreviations Auto Populate Dates Number of Months Between Dates Quarter from a Date Years of Service Change Date Format Compare Dates Time yes Add (Subtract) Hours to Time Add (Subtract) Minutes to Time Add (Subtract) Seconds to Time Add Up time (Total Time) Time Differences Change Time Format Convert Minutes to Hours Convert Time to Decimal Convert Time to Hours Convert Time to Minutes Convert Time to Seconds Military Time Round Time to Nearest 15 Minutes Overtime Calculator Number of Hours Between Times Convert Seconds to Minutes, Hours, or Time Count Hours Worked Time Differences Time Format — Show Minutes Seconds Text yes Add Commas to Cells Get First Word from Text Capitalize First Letter Clean & Format Phone #s Remove Extra Trailing / Leading Spaces Add Spaces to Cell Assign Number Value to Text Combine Cells with Comma Combine First and Last Names Convert Text String to Date Convert Text to Number Extract Text From Cell Get Last Word Remove Unwated Characters Extract Text Before or After Character How to Split Text String by Space, Comma, & More Remove Special Characters Remove First Characters from Left Substitute Multiple Values Switch First & Last Names w/ Commas Remove Specific Text from a Cell Extract Text Between Characters (Ex. Parenthesis) Add Leading Zeros to a Number Remove Line Breaks from Text Remove all Numbers from Text Reverse Text Remove Non-Numeric Characters Remove Last Character(s) From Right Separate First and Last Names Separate Text & Numbers Round yes Round Formulas Round Price to Nearest Dollar or Cent Round to Nearest 10, 100, or 1000 Round to Nearest 5 or .5 Round Percentages Round to Significant Figures Count yes Count Blank and Non-blank Cells Count Cells Between Two Numbers Count Cells not Equal to Count if Cells are in Range Count Times Word Appears in Cell Count Words in Cell Count Specific Characters in Column Count Total Number of Characters in Column Count Cells that Equal one of two Results Count Cells that do not Contain Count Cells that Contain Specific Text Count Unique Values in Range Countif — Multiple Criteria Count Total Number of Cells in Range Count Cells with Any Text Count Total Cells in a Table Lookup yes Two Dimensional VLOOKUP VLOOKUP Simple Example Vlookup — Multiple Matches Case Sensitive Lookup Case Sensitive VLOOKUP Sum if — VLOOKUP Case Sensitive Lookup Case Sensitive VLOOKUP Find Duplicates w/ VLOOKUP or MATCH INDEX MATCH MATCH Lookup — Return Cell Address (Not Value) Lookup Last Value in Column or Row Reverse VLOOKUP (Right to Left) Risk Score Bucket with VLOOKUP Sum with a VLOOKUP Function VLOOKUP & INDIRECT VLOOKUP Concatenate VLOOKUP Contains (Partial Match) 17 Reasons Why Your XLOOKUP is Not Working Double (Nested) XLOOKUP — Dynamic Columns IFERROR (& IFNA) XLOOKUP Lookup Min / Max Value Nested VLOOKUP Top 11 Alternatives to VLOOKUP (Updated 2022!) VLOOKUP – Dynamic Column Reference VLOOKUP – Fix #N/A Error VLOOKUP – Multiple Sheets at Once VLOOKUP & HLOOKUP Combined VLOOKUP & MATCH Combined VLOOKUP Between Worksheets or Spreadsheets VLOOKUP Duplicate Values VLOOKUP Letter Grades VLOOKUP Return Multiple Columns VLOOKUP Returns 0? Return Blank Instead VLOOKUP w/o #N/A Error XLOOKUP Multiple Sheets at Once XLOOKUP Between Worksheets or Spreadsheets XLOOKUP by Date XLOOKUP Duplicate Values XLOOKUP Multiple Criteria XLOOKUP Return Multiple Columns XLOOKUP Returns 0? Return Blank Instead XLOOKUP Text XLOOKUP with IF XLOOKUP With If Statement Misc. yes Sort Multiple Columns Use Cell Value in Formula Percentage Change Between Numbers Percentage Breakdown Rank Values Add Spaces to Cell CAGR Formula Average Time Decimal Part of Number Integer Part of a Number Compare Items in a List Dealing with NA() Errors Get Worksheet Name Wildcard Characters Hyperlink to Current Folder Compound Interest Formula Percentage Increase Create Random Groups Sort with the Small and Large Functions Non-volatile Function Alternatives Decrease a Number by a Percentage Calculate Percent Variance Profit Margin Calculator Convert Column Number to Letter Get Full Address of Named Range Insert File Name Insert Path Latitute / Longitude Functions Replace Negative Values Reverse List Range Convert State Name to Abbreviation Create Dynamic Hyperlinks Custom Sort List with Formula Data Validation — Custom Formulas Dynamic Sheet Reference (INDIRECT) Reference Cell in Another Sheet or Workbook Get Cell Value by Address Get Worksheet Name Increment Cell Reference List Sheet Names List Skipped Numbers in Sequence Return Address of Max Value in Range Search by Keywords Select Every Other (or Every nth) Row Basics yes Cell Reference Basics — A1, R1C1, 3d, etc. Add Up (Sum) Entire Column or Row Into to Dynamic Array Formulas Conversions yes Convert Time Zones Convert Celsius to Fahrenheit Convert Pounds to Kilograms Convert Time to Unix Time Convert Feet to Meters Convert Centimeters to Inches Convert Kilometers to Miles Convert Inches to Feet Convert Date to Julian Format Convert Column Letter to Number Tests yes Test if a Range Contains any Text Test if any Cell in Range is Number Test if a Cell Contains a Specific Value Test if Cell Contains Any Number Test if Cell Contains Specific Number Test if Cell is Number or Text If yes Percentile If Subtotal If Sumproduct If Large If and Small If Median If Concatentate If Max If Rank If TEXTJOIN If Sum yes Sum if — Begins With / Ends With Sum if — Month or Year to Date Sum if — By Year Sum if — Blank / Non-Blank Sum if — Horizontal Sum Count / Sum If — Cell Color INDIRECT Sum Sum If — Across Multiple Sheets Sum If — By Month Sum If — Cells Not Equal To Sum If — Not Blank Sum if — Between Values Sum If — Week Number Sum Text Sum if — By Category or Group Sum if — Cell Contains Specific Text (Wildcards) Sum if — Date Rnage Sum if — Dates Equal Sum if — Day of Week Sum if — Greater Than Sum if — Less Than Average yes Average Non-Zero Values Average If — Not Blank Average — Ignore 0 Average — Ignore Errors Math yes Multiplication Table Cube Roots nth Roots Square Numbers Square Roots Calculations yes Calculate a Ratio Calculate Age KILLLLLLL Calculate Loan Payments GPA Formula Calculate VAT Tax How to Grade Formulas Find yes Find a Number in a Column / Workbook Find Most Frequent Numbers Find Smallest n Values Find nth Occurance of Character in Text Find and Extract Number from String Find Earliest or Latest Date Based on Criteria Find First Cell with Any Value Find Last Row Find Last Row with Data Find Missing Values Find Largest n Values Most Frequent Number Conditional Formatting yes Conditional Format — Dates & Times Conditional Format — Highlight Blank Cells New Functions XLOOKUP Replaces VLOOKUP, HLOOKUP, and INDEX / MATCH Logical yes AND Checks whether all conditions are met. TRUE/FALSE IF If condition is met, do something, if not, do something else. IFERROR If result is an error then do something else. NOT Changes TRUE to FALSE and FALSE to TRUE. OR Checks whether any conditions are met. TRUE/FALSE XOR Checks whether one and only one condition is met. TRUE/FALSE Lookup & Reference yes FALSE The logical value: FALSE. TRUE The logical value: TRUE. ADDRESS Returns a cell address as text. AREAS Returns the number of areas in a reference. CHOOSE Chooses a value from a list based on it’s position number. COLUMN Returns the column number of a cell reference. COLUMNS Returns the number of columns in an array. HLOOKUP Lookup a value in the first row and return a value. HYPERLINK Creates a clickable link. INDEX Returns a value based on it’s column and row numbers. INDIRECT Creates a cell reference from text. LOOKUP Looks up values either horizontally or vertically. MATCH Searches for a value in a list and returns its position. OFFSET Creates a reference offset from a starting point. ROW Returns the row number of a cell reference. ROWS Returns the number of rows in an array. TRANSPOSE Flips the oriention of a range of cells. VLOOKUP Lookup a value in the first column and return a value. Date & Time yes DATE Returns a date from year, month, and day. DATEDIF Number of days, months or years between two dates. DATEVALUE Converts a date stored as text into a valid date DAY Returns the day as a number (1-31). DAYS Returns the number of days between two dates. DAYS360 Returns days between 2 dates in a 360 day year. EDATE Returns a date, n months away from a start date. EOMONTH Returns the last day of the month, n months away date. HOUR Returns the hour as a number (0-23). MINUTE Returns the minute as a number (0-59). MONTH Returns the month as a number (1-12). NETWORKDAYS Number of working days between 2 dates. NETWORKDAYS.INTL Working days between 2 dates, custom weekends. NOW Returns the current date and time. SECOND Returns the second as a number (0-59) TIME Returns the time from a hour, minute, and second. TIMEVALUE Converts a time stored as text into a valid time. TODAY Returns the current date. WEEKDAY Returns the day of the week as a number (1-7). WEEKNUM Returns the week number in a year (1-52). WORKDAY The date n working days from a date. WORKDAY.INTL The date n working days from a date, custom weekends. YEAR Returns the year. YEARFRAC Returns the fraction of a year between 2 dates. Engineering yes CONVERT Convert number from one unit to another. Financial yes FV Calculates the future value. PV Calculates the present value. NPER Calculates the total number of payment periods. PMT Calculates the payment amount. RATE Calculates the interest Rate. NPV Calculates the net present value. IRR The internal rate of return for a set of periodic CFs. XIRR The internal rate of return for a set of non-periodic CFs. PRICE Calculates the price of a bond. YIELD Calculates the bond yield. INTRATE The interest rate of a fully invested security. Information yes CELL Returns information about a cell. ERROR.TYPE Returns a value representing the cell error. ISBLANK Test if cell is blank. TRUE/FALSE ISERR Test if cell value is an error, ignores #N/A. TRUE/FALSE ISERROR Test if cell value is an error. TRUE/FALSE ISEVEN Test if cell value is even. TRUE/FALSE ISFORMULA Test if cell is a formula. TRUE/FALSE ISLOGICAL Test if cell is logical (TRUE or FALSE). TRUE/FALSE ISNA Test if cell value is #N/A. TRUE/FALSE ISNONTEXT Test if cell is not text (blank cells are not text). TRUE/FALSE ISNUMBER Test if cell is a number. TRUE/FALSE ISODD Test if cell value is odd. TRUE/FALSE ISREF Test if cell value is a reference. TRUE/FALSE ISTEXT Test if cell is text. TRUE/FALSE N Converts a value to a number. NA Returns the error: #N/A. TYPE Returns the type of value in a cell. Math yes ABS Calculates the absolute value of a number. AGGREGATE Define and perform calculations for a database or a list. CEILING Rounds a number up, to the nearest specified multiple. COS Returns the cosine of an angle. DEGREES Converts radians to degrees. DSUM Sums database records that meet certain criteria. EVEN Rounds to the nearest even integer. EXP Calculates the exponential value for a given number. FACT Returns the factorial. FLOOR Rounds a number down, to the nearest specified multiple. GCD Returns the greatest common divisor. INT Rounds a number down to the nearest integer. LCM Returns the least common multiple. LN Returns the natural logarithm of a number. LOG Returns the logarithm of a number to a specified base. LOG10 Returns the base-10 logarithm of a number. MOD Returns the remainder after dividing. MROUND Rounds a number to a specified multiple. ODD Rounds to the nearest odd integer. PI The value of PI. POWER Calculates a number raised to a power. PRODUCT Multiplies an array of numbers. QUOTIENT Returns the integer result of division. RADIANS Converts an angle into radians. RAND Calculates a random number between 0 and 1. RANDBETWEEN Calculates a random number between two numbers. ROUND Rounds a number to a specified number of digits. ROUNDDOWN Rounds a number down (towards zero). ROUNDUP Rounds a number up (away from zero). SIGN Returns the sign of a number. SIN Returns the sine of an angle. SQRT Calculates the square root of a number. SUBTOTAL Returns a summary statistic for a series of data. SUM Adds numbers together. SUMIF Sums numbers that meet a criteria. SUMIFS Sums numbers that meet multiple criteria. SUMPRODUCT Multiplies arrays of numbers and sums the resultant array. TAN Returns the tangent of an angle. TRUNC Truncates a number to a specific number of digits. Stats yes AVERAGE Averages numbers. AVERAGEA Averages numbers. Includes text & FALSE =0, TRUE =1. AVERAGEIF Averages numbers that meet a criteria. AVERAGEIFS Averages numbers that meet multiple criteria. CORREL Calculates the correlation of two series. COUNT Counts cells that contain a number. COUNTA Count cells that are non-blank. COUNTBLANK Counts cells that are blank. COUNTIF Counts cells that meet a criteria. COUNTIFS Counts cells that meet multiple criteria. FORECAST Predict future y-values from linear trend line. FREQUENCY Counts values that fall within specified ranges. GROWTH Calculates Y values based on exponential growth. INTERCEPT Calculates the Y intercept for a best-fit line. LARGE Returns the kth largest value. LINEST Returns statistics about a trendline. MAX Returns the largest number. MEDIAN Returns the median number. MIN Returns the smallest number. MODE Returns the most common number. PERCENTILE Returns the kth percentile. PERCENTILE.INC Returns the kth percentile. Where k is inclusive. PERCENTILE.EXC Returns the kth percentile. Where k is exclusive. QUARTILE Returns the specified quartile value. QUARTILE.INC Returns the specified quartile value. Inclusive. QUARTILE.EXC Returns the specified quartile value. Exclusive. RANK Rank of a number within a series. RANK.AVG Rank of a number within a series. Averages. RANK.EQ Rank of a number within a series. Top Rank. SLOPE Calculates the slope from linear regression. SMALL Returns the kth smallest value. STDEV Calculates the standard deviation. STDEV.P Calculates the SD of an entire population. STDEV.S Calculates the SD of a sample. STDEVP Calculates the SD of an entire population TREND Calculates Y values based on a trendline. Text yes CHAR Returns a character specified by a code. CLEAN Removes all non-printable characters. CODE Returns the numeric code for a character. CONCATENATE Combines text together. DOLLAR Converts a number to text in currency format. EXACT Test if cells are exactly equal. Case-sensitive. TRUE/FALSE FIND Locates position of text within a cell.Case-sensitive. LEFT Truncates text a number of characters from the left. LEN Counts number of characters in text. LOWER Converts text to lower case. MID Extracts text from the middle of a cell. PROPER Converts text to proper case. REPLACE Replaces text based on it’s location. REPT Repeats text a number of times. RIGHT Truncates text a number of characters from the right. SEARCH Locates position of text within a cell.Not Case-sensitive. SUBSTITUTE Finds and replaces text. Case-sensitive. TEXT Converts a value into text with a specific number format. TRIM Removes all extra spaces from text. UPPER Converts text to upper case. VALUE Converts a number stored as text into a number.

Понравилась статья? Поделить с друзьями:
  • Excel if with multiple or conditions
  • Excel if with font color
  • Excel if with date range
  • Excel if with color fill
  • Excel if with and or condition