Excel if case when


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:

case statement in Excel

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

Оператор Select Case, выполняющий одну или более групп операторов VBA Excel в зависимости от значения управляющего выражения. Синтаксис, компоненты, примеры.

Оператор Select Case используется в VBA Excel для управления отдельными блоками операторов в зависимости от значения управляющего выражения (переменной) и сравнительных условий, задаваемых ключевым словом Case.

Синтаксис оператора Select Case

Select Case выражение

    Case условие 1

        [операторы 1]

    Case условие 2

        [операторы 2]

    Case условие n

        [операторы n]

    Case Else

        [операторы]

End Select

Компоненты оператора Select Case

  • выражение – любое числовое или строковое выражение, переменная;
  • условие – диапазон значений или выражение с операторами сравнения и ключевым словом Is*;
  • операторы – блок операторов VBA Excel, который выполняется при вхождении значения управляющего выражения в диапазон, заданный в условии, или при возврате выражением с операторами сравнения значения True;
  • блок операторов после ключевой фразы Case Else** выполняется в том случае, если в предыдущих условиях Case не будет найдено совпадений со значением управляющего выражения (переменной).

* Редактор VBA Excel автоматически добавляет ключевое слово Is в условия с операторами сравнения.
** Компонент Case Else с соответствующим блоком операторов необязательны, но рекомендуется их использовать для обработки непредвиденных значений управляющего выражения (переменной).

Примеры использования в VBA Excel

Пример 1

Пример использования оператора Select Case с операторами сравнения в условиях:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Sub primer1()

Dim a As Integer, b As String

a = InputBox(«Введите число от 1 до 5», «Пример 1», 1)

    Select Case a

        Case Is = 1

            b = «один»

        Case Is = 2

            b = «два»

        Case Is = 3

            b = «три»

        Case Is = 4

            b = «четыре»

        Case Is = 5

            b = «пять»

        Case Else

            b = «Число не входит в диапазон от 1 до 5»

    End Select

MsgBox b

End Sub

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

Пример 2

Пример использования оператора Select Case с заданным диапазоном в условиях:

Sub primer2()

Dim a As Integer, b As String

a = InputBox(«Введите число от 1 до 30», «Пример 2», 1)

    Select Case a

        Case 1 To 10

            b = «Число « & a & » входит в первую десятку»

        Case 11 To 20

            b = «Число « & a & » входит во вторую десятку»

        Case 21 To 30

            b = «Число « & a & » входит в третью десятку»

        Case Else

            b = «число « & a & » не входит в первые три десятки»

    End Select

MsgBox b

End Sub

Для решения подобной задачи в VBA Excel можно использовать многострочную конструкцию оператора If…Then…Else, но решение с Select Case выглядит изящней.

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.

Excel Case Statements: SWITCH Function Versus Nested IF

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.

Excel Case Statements: SWITCH Function Versus Nested IF

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.

Excel Case Statements: SWITCH Function Versus Nested IF

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.

Excel Case Statements: SWITCH Function Versus Nested IF

  • Редакция Кодкампа

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:

оператор case в Excel

Обратите внимание, что эта формула возвращает следующие значения в столбце B:

  • « Guard », если столбец A содержит «G»
  • « Вперед », если столбец A содержит «F»
  • « По центру », если столбец A содержит «C»
  • « Нет », если столбец A не содержит ни одного из предыдущих значений.

Обратите внимание, что последнее значение в столбце B возвращает значение « Нет », поскольку мы не указали конкретное значение для возврата «Z» в формуле.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные задачи в Excel:

Excel: как найти уникальные значения из нескольких столбцов
Excel: как сопоставить два столбца и вернуть третий

Написано

Редакция Кодкампа

Замечательно! Вы успешно подписались.

Добро пожаловать обратно! Вы успешно вошли

Вы успешно подписались на кодкамп.

Срок действия вашей ссылки истек.

Ура! Проверьте свою электронную почту на наличие волшебной ссылки для входа.

Успех! Ваша платежная информация обновлена.

Ваша платежная информация не была обновлена.

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 with the if function

Formula that uses the IF function

Button image  logical_test: The condition that you want to check.

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

Button image  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)

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

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?

  1. Select the example in this article.

    selecting an example from help in Excel 2013 for Windows

    Selecting an example from Help

  2. Press CTRL+C.

  3. In Excel, create a blank workbook or worksheet.

  4. 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.

  1. 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.

Data

15

9

8

Sprockets

Widgets

Formula

Description (Result)

=AND(A2>A3, A2<A4)

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)

=OR(A2>A3, A2<A4)

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)

=NOT(A2+A3=24)

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

=NOT(A5=»Sprockets»)

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

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

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.

Top of Page

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?

  1. Select the example in this article.

    Important: Do not select the row or column headers.

    selecting an example from help in Excel 2013 for Windows

    Selecting an example from Help

  2. Press CTRL+C.

  3. In Excel, create a blank workbook or worksheet.

  4. 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.

  1. 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.

Data

15

9

8

Sprockets

Widgets

Formula

Description (Result)

=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<=15), «OK», «Not OK»)

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

=IF(A5<>»SPROCKETS», «OK», «Not OK»)

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

=IF(AND(A2>A3, A2<A4), «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(OR(A2>A3, A2<A4), «OK», «Not 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.

Top of Page

Понравилась статья? Поделить с друзьями:
  • Excel if bold text
  • Excel if between range
  • Excel if begins with function
  • Excel if any value then
  • Excel if any value in column