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])
For example:
-
=IF(A2>B2,»Over Budget»,»OK»)
-
=IF(A2=B2,B4-A4,»»)
Argument name |
Description |
---|---|
logical_test (required) |
The condition you want to test. |
value_if_true (required) |
The value that you want returned if the result of logical_test is TRUE. |
value_if_false (optional) |
The value that you want returned if the result of logical_test is FALSE. |
Simple IF examples
-
=IF(C2=”Yes”,1,2)
In the above example, cell D2 says: IF(C2 = Yes, then return a 1, otherwise return a 2)
-
=IF(C2=1,”Yes”,”No”)
In this example, the formula in cell D2 says: IF(C2 = 1, then return Yes, otherwise return No)As you see, the IF function can be used to evaluate both text and values. It can also be used to evaluate errors. You are not limited to only checking if one thing is equal to another and returning a single result, you can also use mathematical operators and perform additional calculations depending on your criteria. You can also nest multiple IF functions together in order to perform multiple comparisons.
-
=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”)
-
=IF(C2>B2,C2-B2,0)
In the above illustration, instead of returning a text result, we are going to return a mathematical calculation. So the formula in E2 is saying IF(Actual is Greater than Budgeted, then Subtract the Budgeted amount from the Actual amount, otherwise return nothing).
-
=IF(E7=”Yes”,F5*0.0825,0)
In this example, the formula in F7 is saying IF(E7 = “Yes”, then calculate the Total Amount in F5 * 8.25%, otherwise no Sales Tax is due so return 0)
Note: If you are going to use text in formulas, you need to wrap the text in quotes (e.g. “Text”). The only exception to that is using TRUE or FALSE, which Excel automatically understands.
Common problems
Problem |
What went wrong |
---|---|
0 (zero) in cell |
There was no argument for either value_if_true or value_if_False arguments. To see the right value returned, add argument text to the two arguments, or add TRUE or FALSE to the argument. |
#NAME? in cell |
This usually means that the formula is misspelled. |
Need more help?
You can always ask an expert in the Excel Tech Community or get support in the Answers community.
See Also
IF function — nested formulas and avoiding pitfalls
IFS function
Using IF with AND, OR and NOT functions
COUNTIF function
How to avoid broken formulas
Overview of formulas in Excel
Need more help?
17 авг. 2022 г.
читать 1 мин
Оператор case — это тип оператора, который проходит через условия и возвращает значение при выполнении первого условия.
Самый простой способ реализовать оператор case в Excel — использовать функцию ПЕРЕКЛЮЧАТЕЛЬ() , которая использует следующий базовый синтаксис:
=SWITCH( A2 , "G", "Guard", "F", "Forward", "C", "Center", "None")
Эта конкретная функция просматривает ячейку A2 и возвращает следующее значение:
- « На страже », если ячейка A2 содержит «G»
- « Вперед », если ячейка A2 содержит «F»
- « По центру », если ячейка A2 содержит «C»
- « Нет », если ячейка A2 не содержит ни одного из предыдущих значений.
В следующем примере показано, как использовать эту функцию на практике.
Пример: оператор Case в Excel
Предположим, у нас есть следующий список баскетбольных позиций:
Мы будем использовать следующую функцию SWITCH() , чтобы вернуть определенное имя позиции в столбце B на основе значения в столбце A:
=SWITCH( A2 , "G", "Guard", "F", "Forward", "C", "Center", "None")
Мы введем эту формулу в ячейку B2 , а затем скопируем и вставим ее в каждую оставшуюся ячейку в столбце B:
Обратите внимание, что эта формула возвращает следующие значения в столбце B:
- « Guard », если столбец A содержит «G»
- « Вперед », если столбец A содержит «F»
- « По центру », если столбец A содержит «C»
- « Нет », если столбец A не содержит ни одного из предыдущих значений.
Обратите внимание, что последнее значение в столбце B возвращает значение « Нет », поскольку мы не указали конкретное значение для возврата «Z» в формуле.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные задачи в Excel:
Excel: как найти уникальные значения из нескольких столбцов
Excel: как сопоставить два столбца и вернуть третий
Написано
Замечательно! Вы успешно подписались.
Добро пожаловать обратно! Вы успешно вошли
Вы успешно подписались на кодкамп.
Срок действия вашей ссылки истек.
Ура! Проверьте свою электронную почту на наличие волшебной ссылки для входа.
Успех! Ваша платежная информация обновлена.
Ваша платежная информация не была обновлена.
Excel case statements can be handled with either SWITCH function or nested IF statements. A popular use for the IF function is creating nested formulas that can check for various criteria. However, nested IF statements can get pretty complicated and cumbersome when dealing with several conditions.
Excel has introduced the SWITCH function which can essentially do what nested IF functions can, using only one function. In this article, we’re going to take a look at the differences between these two Excel case statements and how you can compare several conditions more efficiently. You can download our sample workbook below.
The Basics of the IF Function
The IF function is one of the most popular functions of Excel. It allows creating conditions, on which a logic can be implemented. The IF function gives a TRUE or FALSE result depending on the outcome of the condition check.
There really are no other alternatives to the IF function, therefore, users typically prefer using nested structures which means using the function over and over again. Let’s see how this works on an example. Below is a set of IF formulas inside one another.
This formula checks for 4 conditions, «S», «M», «L» and “other” to give a measurement. To do this, we need 2 extra IF functions which are connected to the negative result argument of the previous one. The logic in this structure is to continue the formula if first condition is not met. Then look at the second condition and continue likewise until the criteria is satisfied.
As you can imagine, nested IF statements become harder to read and maintain as the number of condition increase. The SWITCH function was introduced as a user-friendly alternative to alleviate the burden of too many IF formulas.
The Better Alternative: SWITCH Function
The SWITCH function was first introduced in Excel 2016 not to replace the IF function, but instead as an alternative to nested IF formulas. The SWITCH function evaluates the value in its first argument against the value-result pairs, and returns the result from the matched pair if there is a match, or the default value if there are none.
Syntax
=SWITCH(expression, value1, result1, [default or value2, result2],…[default or value3, result3])
Argument | Description |
expression | Expression is the value (i.e. a number, date, or text) that will be compared against value1…value126. |
value1…value126 | valueN (nth value parameter) is the value that will be compared against an expression. |
result1…result126 | resultN (nth result parameter) is the value to be returned when the corresponding valueN argument that matches the expression. resultN must be entered for each corresponding valueN argument. |
default | (Optional) default is the value to be returned in case there are no matches in any valueN expressions. The default has no corresponding resultN expression. default must be the final argument of the function.
If a default value is not defined and no matches are found, the formula returns #N/A error. |
Note: Because functions are limited to 254 parameters, you can use up to 126 pairs of value and result arguments.
SWITCH vs. IF
Let’s revisit the measurement example using the SWITCH function this time.
The first advantage is the number of formulas used in this argument. When creating a nested IF statement, you need to be actively tracing where you’re at in the formula at each step. Using the SWITCH formula, you can do what 126 IF functions could, using a single function.
Note: It is not advisable to create a SWITCH function that contains 126 value-result pairs. Instead, try using the VLOOKUP function for matching large condition sets. For more information about the VLOOKUP, check out our HOW TO VLOOKUP article.
The second advantage comes from the fact that your formula is going to be much shorter in most cases. Formula text with the SWITCH function is shorter, and easier to read.
A case statement is a type of statement that goes through conditions and returns a value when the first condition is met.
The easiest way to implement a case statement in Excel is by using the SWITCH() function, which uses the following basic syntax:
=SWITCH(A2, "G", "Guard", "F", "Forward", "C", "Center", "None")
This particular function looks at cell A2 and returns the following value:
- “Guard” if cell A2 contains “G”
- “Forward” if cell A2 contains “F”
- “Center” if cell A2 contains “C”
- “None” if cell A2 does not contain any of the previous values
The following example shows how to use this function in practice.
Example: Case Statement in Excel
Suppose we have the following list of basketball positions:
We’ll use the following SWITCH() function to return a specific position name in column B based on the value in column A:
=SWITCH(A2, "G", "Guard", "F", "Forward", "C", "Center", "None")
We’ll type this formula into cell B2 and then copy and paste it down to every remaining cell in column B:
Notice that this formula returns the following values in column B:
- “Guard” if column A contains “G”
- “Forward” if column A contains “F”
- “Center” if column A contains “C”
- “None” if column A does not contain any of the previous values
Notice that the last value in column B returns a value of “None” since we didn’t specify a specific value to return for “Z” in the formula.
Additional Resources
The following tutorials explain how to perform other common tasks in Excel:
Excel: How to Find Unique Values from Multiple Columns
Excel: How to Match Two Columns and Return a Third
This Excel tutorial explains how to use the Excel CASE statement with syntax and examples.
Description
The Microsoft Excel CASE statement has the functionality of an IF-THEN-ELSE statement.
The CASE statement is a built-in function in Excel that is categorized as a Logical Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.
Syntax
The syntax for the CASE statement in Microsoft Excel is:
Select Case test_expression Case condition_1 result_1 Case condition_2 result_2 ... Case condition_n result_n [ Case Else result_else ] End Select
Parameters or Arguments
- test_expression
- A string or numeric value. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, … condition_n)
- condition_1, … condition_n
- Conditions that are evaluated in the order listed. Once a condition is found to be true, it will execute the corresponding code and not evaluate the conditions any further.
- result_1, … result_n
- The code that is executed once a condition is found to be true.
Returns
The CASE statement executes the corresponding code for the first condition that is found to be TRUE.
If no condition is met, then the Else clause in the CASE statement will be executed. The Else clause is optional.
If the Else clause is omitted and no condition is found to be true, then the CASE statement will do nothing.
Applies To
- Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Type of Function
- VBA function (VBA)
Example (as VBA Function)
The CASE statement can only be used in VBA code in Microsoft Excel.
Let’s look at some Excel CASE statement function examples and explore how to use the CASE statement in Excel VBA code:
Select Case LRegion Case "N" LRegionName = "North" Case "S" LRegionName = "South" Case "E" LRegionName = "East" Case "W" LRegionName = "West" End Select
With the Excel CASE statement, you can also use the To keyword to specify a range of values. For example:
Select Case LNumber Case 1 To 10 LRegionName = "North" Case 11 To 20 LRegionName = "South" Case 21 To 30 LRegionName = "East" Case Else LRegionName = "West" End Select
With the Excel CASE statement, you can also comma delimit values. For example:
Select Case LNumber Case 1, 2 LRegionName = "North" Case 3, 4, 5 LRegionName = "South" Case 6 LRegionName = "East" Case 7, 11 LRegionName = "West" End Select
And finally, with the Excel CASE statement, you can also use the Is keyword to compare values. For example:
Select Case LNumber Case Is < 100 LRegionName = "North" Case Is < 200 LRegionName = "South" Case Is < 300 LRegionName = "East" Case Else LRegionName = "West" End Select