Excel макрос case if

Оператор 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 выглядит изящней.

При создании сложных программ один из ключевых моментов — возможность предусмотреть несколько вариантов развития событий. Самый простой и классический пример — оператор «If … Then … Else … End«, который позволяет выбрать одно из двух действий в зависимости от результатов проверки каких-либо значений. Бывает, что в результате такой проверки необходимо выбрать из множества вариантов. Один из выходов: добавить множество «… ElseIf …», что несколько усложняет синтаксис программы (лёгкость её чтения). Однако это очень мощный оператор, открывающий большие возможности. Подробнее о нём можно узнать здесь.

Альтернативой оператору «If … End» служит оператор «Select Case» (с английского «Select Case» можно перевести как «Выбор Ситуации»), который упрощает восприятие кода «на глаз». И если «If … End» оператор в каждом своём «ElseIf» вынужден обращаться к проверяемым значениям снова и снова (допустим, выражение каждый раз одинаковое), то «Select Case» делает это только один раз, что позволяет последнему на больших массивах данных работать быстрее. Этот оператор позволяет удобно задать ветвление программы из одной точки в большое количество веток. То есть в основном применяется при множественных условиях проверки, когда проверяемых условий больше двух.

Структура оператора «Select Case».

Давайте посмотрим, как выглядит обобщённая структура оператора и разберём, что есть что (разные примеры частного использования кода будут приведены в конце статьи):

Select Case [Проверяемое Значение]
    Case [Конкретное Значение]
        [Некоторое Действие]
    Case Else
        [Некоторое Действие Х]
End Select

В качестве куска [Значение] можно вставить любую переменную или свойство, значение которой или которого Вы можете проверить. Можно также проверять значение конкретной ячейки. При этом работать можно не только с числами, но и с текстами. И даже с булевыми значениями TRUE/FALSE («Правда» и «Ложь»), о чем знают не все.

[Конкретное Значение] — это то, с чем сравнивается [Проверяемое Значение]. И, если одно удовлетворяет другому, то выполняется [Некоторое Действие]. Есть несколько вариантов записи для блока [Конкретное Значение]. Для текстовых и числовых значений можно записывать разные значения через запятую:

Case 3, 4, 5, "да", "нет"

Для чисел можно выбирать диапазоны:

Case 3 to 10 'От 3-х до 10-ти, включая сами 3 и 10.

Также для чисел можно использовать логический оператор сравнения вместе с частицей «Is«:

Case Is < 2 'Меньше 2, НЕ включая 2
Case Is = 3 'Равно 3-м. Избыточная запись, достаточно Case 3
Case Is >= 4 'Больше либо равно 4
Case Is <> 0 'Не равно нулю

Допустимо использовать и логические операторы, что позволит предусматривать сложнейшие случаи и проводить параллельные сравнения с другими переменными. Кроме оператора «Or», который заменяется обычной запятой.

Case ... And ...
Case Not ...

[Некоторое Действие] может быть абсолютно любым. Если вы его пропускаете — то для данного случая программа будет бездействовать. «Case [Конкретное Значение]» вместе с частью [Некоторое Действие] складываются в один блок:

Case [Конкретное Значение]
    [Некоторое Действие]

Таких блоков может быть любое количество, которое уложится в предельные размеры процедуры (она должна весить не более 64 килобайт). Полезно знать, что VBA просматривает соответствие [Конкретного Значения] и [Проверяемого Значения] вдоль по блокам сверху вниз. То есть, у Вас может быть два блока с одинаковым «Case«, но выполнится только тот, который будет раньше найден программой при просмотре кода сверху вниз.

Case Else — это все другие случаи, которые не подошли ни под одно другое [Конкретное Значение] во всех блоках оператора «Select Case«. Если блок «Case Else» отсутствует и ни один другой блок не подошёл, то программа делает логичное «ничего». Case Else должен быть последним проверяемым случаем среди всех блоков проверки в операторе. После него других блоков быть не должно, иначе получим синтаксическую ошибку «Case without Select Case«.

В конце оператора должен стоять «End Select«, который служит «точкой» в «предложении» оператора.

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

Рассмотрим несколько примеров использования кода и начнём с самого простого. В первом примере в зависимости от значения Х выводится сообщение.

Sub SelectCase_example_1()

Dim X As Long
X = 1 'Можете изменять эту цифру и смотреть, что получится.

Select Case X
    Case 1
        MsgBox "Один"
    Case 2
        MsgBox "Два"
    Case 3
        MsgBox "Три"
    Case Else
        MsgBox "Выбрано что-то другое"
End Select

End Sub

Второй пример показывает некоторые виды записи проверяемого значения. В зависимости от количества листов в книге с макросом выводится разное сообщение. Обратите внимание, что если листов в книге 7, то первым сработает “Case 7”, хотя условие “Case 5 to 12” тоже подходит, но стоит позже.

Sub SelectCase_example_2()

'Введём переменную и посчитаем количество листов в текущей книге:
Dim X As Long
X = ThisWorkbook.Sheets.Count

Select Case X 'В зависимости от количества листов в книге выведем сообщение.
    Case 1 'Если 1 лист, то...
        MsgBox "Один лист в книге"
    Case 2, 3, 4 'Если листов 2 или 3 или 4
        MsgBox "Несколько листов в книге"
    Case 7 'Если листов 7
        MsgBox "Красивое количество листов"
    Case 5 To 12 'Если листов от 5 до 12
        MsgBox "Почти брошюра"
    Case Is >= 14 'Если листов больше либо равно 14
        MsgBox "Листов как в фолианте"
    Case Else 'Все остальные случаи, а именно 13
        MsgBox "Чёртова дюжина листов"
End Select

End Sub

Третий пример ориентируется на булево значение TRUE или FALSE. Проверяется, виден или скрыт последний лист в текущей книге с макросом. С помощью двоеточия может заменяться перенос строки для получения более изящного кода.

Sub SelectCase_example_3()

'Введём переменную и привяжем её к последнему листу в книге:
Dim shtX As Worksheet: Set shtX = ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

Select Case shtX.Visible 'Проверим, скрыт ли лист или нет
    Case True: MsgBox "Последний лист в книге доступен" 'Если последний лист виден
    Case False: MsgBox "Последний лист в книге скрыт" 'Если последний лист скрыт
End Select

End Sub

Четвёртый пример показывает, что «Case» может ориентироваться и на другие переменные. В данном случае будем проверять равенство трёх переменных с помощью логического оператора «And»:

Sub SelectCase_example_4()

'Введём несколько переменных:
Dim X%, Y%, Z%
'Приравняем всех к тройке:
X = 3: Y = 3: Z = 3

Select Case True 'Проверим равенство всех переменных
    Case Z = X And Y = X: MsgBox "Все равны" 'Если все равны
    Case Else: MsgBox "Кто-то отличается" 'Если хоть кто-то отличается
End Select

End Sub

Пятый пример показывает, как через запятую в проверяемом значении для «Case» можно указать целый набор чисел. Допустим, есть некоторая функция и мы проверяем, может ли наше число в этой функции использоваться. По условию, нас устраивают числа в диапазоне от 5 (не включая 5) до минус бесконечности, от 12 до 15 включая концы и от 20 (включая 20) до плюс бесконечности.

Sub SelectCase_example_5()

'Введём переменную и дадим ей значение вручную
Dim X As Double
X = InputBox("Введите числовое значение переменной Х")

Select Case X 'Проверим, подходит ли некоторой воображаемой функции наше значение
    Case Is < 5, Is >= 20, 12 To 15 'Диапазон подходящих значений
        MsgBox "Действительное значение для некоторой функции"
    Case Else 'Не подходящие значения
        MsgBox "Значение не может быть использовано в некоторой функции"
End Select

End Sub

Подводя черту, замечу, что оператор «Select Case» по структуре довольно прост и удобен в использовании. Он менее гибок по сравнению с «If … End», если по ходу проверок требуется менять проверяемое значение, но значительно выигрывает при разнообразных проверках одного и того же выражения. Для чего собственно и был создан.

Спасибо за внимание.

Статью c примерами составил Роман «Rioran» Воронов для www.excelworld.ru

The Select Case statement is an alternative way to write If/ElseIf statements.

You will find a Select Case statement equivalent in most popular programming languages. In many languages, the equivalent statement is the Switch statement. For example, the languages Java, C#, C++ and Javascript all have a switch statement.

Case Statement Quick Guide

Case Options Description Examples
Is Use with operators =, >,<,<>,>=,<= Case Is = 5
Case Is = «Apple»
Case Is > 5
Case Is <= 10
To Use for a range of numbers Case 5 To 10
Case 85 To 99
Case «A» To «D»
Comma Use the comma to include multiple conditions for one case Case 1, 3, 9, 11
Case 1, Is > 20, 10 To 15
No operator The same as «Is =» Case 5
Case «Apple»

Select Case Format

The format of the VBA Select Case statement is a follows:

Select Case [variable]
    Case [condition 1]
        [Statement 1]
    Case [condition 2]
        [Statement 2]
    Case [condition n]
        [Statement n]
    Case Else
        [Statement else]
End Select

The following is a simple example of using the Select Case Statement:

' https://excelmacromastery.com/
Public Sub Select_Case_Example()

    ' Read value from cell A1 on sheet1
    Dim airportCode As String
    airportCode = Sheet1.Range("A1").Value
    
    ' Print the name of the airport to the Immediate Window(Ctrl + G)
    Select Case airportCode
        Case "LHR"
            Debug.Print "London Heathrow"
        Case "JFK"
            Debug.Print "John F Kennedy"
        Case "SIN"
            Debug.Print "Singapore"
    End Select

End Sub

The code below is the equivalent If statement:

' https://excelmacromastery.com/
Public Sub If_Example()

    ' Read value from cell A1 on sheet1
    Dim airportCode As String
    airportCode = Sheet1.Range("A1").Value
    
    ' Print the name of the airport to the Immediate Window(Ctrl + G)
    If airportCode = "LHR" Then
            Debug.Print "London Heathrow"
    ElseIf airportCode = "JFK" Then
            Debug.Print "John F Kennedy"
    ElseIf airportCode = "SIN" Then
            Debug.Print "Singapore"
    End If

End Sub

We use the Select Case statement because it provides us with more flexibility than an If statement. We will see more above this below.

Using the Colon Operator

We can use the colon symbol “:” to make our Case statements look neater. The colon symbol allows us to place two lines VBA lines of code on one line. They are still treated as two lines by VBA but the code looks neater:

Select Case airportCode
    Case "LHR": Debug.Print "London Heathrow"
    Case "JFK": Debug.Print "John F Kennedy"
    Case "SIN": Debug.Print "Singapore"
End Select

Code Between Case Statements

In the previous examples we had just one line of code for each Case Condition. You can have as many lines of code as you want. However it is good practice to keep it to one line if possible. The purpose of the Select Case statement is to make the code readable.

In the following example, we have multiple lines of code for the Case “London”:

' https://excelmacromastery.com/
Sub MultiLine()

    Dim city As String
    city = Sheet1.Range("A1").Value

    Select Case city
        Case "London"
            ' would be better in another sub
            Count = Count + 1
            x = 6
            a = 5
        Case Else
            Debug.Print "other city"
    End Select
    
End Sub

If we have multiple lines, we could place them in a sub and then call this sub:

Select Case city
    Case "London"
        Call UpdateValues
    Case Else
        Debug.Print "other city"
End Select

Case Else

The Case Else statement is used with Select Case. It is the equivalent of the Else statement used with If. In simple terms, it means “if no other options were selected then select this one”.

Case Else is often used to check that a valid value was supplied. In the example below, it is used to check if the Airport Code was valid:

' https://excelmacromastery.com/
Public Sub Select_Case_Else()

    ' Read value from cell A1 on sheet1
    Dim airportCode As String
    airportCode = Sheet1.Range("A1").Value
    
    ' Print the name of the airport to the Immediate Window (Ctrl + G)
    Select Case airportCode
        Case "LHR"
            Debug.Print "London Heathrow"
        Case "JFK"
            Debug.Print "John F Kennedy"
        Case "SIN"
            Debug.Print "Singapore"
        Case Else
            MsgBox "The airport code is not valid.", vbInformation
    End Select

End Sub

Using Select Case with Numbers

We can use the To keyword to specify a range of numbers:

' https://excelmacromastery.com/
Select Case marks
    Case 85 To 100
        Debug.Print "High Distinction"
    Case 75 To 84
        Debug.Print "Distinction"
    Case 55 To 74
        Debug.Print "Credit"
    Case 40 To 54
        Debug.Print "Pass"
    Case Else
         Debug.Print "Fail"
End Select

Select Case Is

We can use the Is keyword if we want to use the operators like =, >,< etc.

In the below example, I have rewritten the previous Select Case statement using Is instead of To:

' https://excelmacromastery.com/
Select Case marks

    Case Is >= 85
        Debug.Print "High Distinction"
    Case Is >= 75
        Debug.Print "Distinction"
    Case Is >= 55
        Debug.Print "Credit"
    Case Is >= 40
        Debug.Print "Pass"
    Case Else
        ' For all other marks
        Debug.Print "Fail"
        
End Select

We don’t need to use the Is keyword when using equals. The two lines below are equivalent:

Case "LHR"
Case Is = "LHR"

So are these two:

Case 10
Case Is = 10

Select Case Multiple Values

We can have multiple case conditions on one line. We simply use the comma to separate them:

Case Is > 85, 70 To 75, 83
Case 2, 4, 6, 8
    Debug.Print "Even numbers"
Case 1, 3, 5, 7
    Debug.Print "Odd numbers"

The following is an example of using multiple strings:

' https://excelmacromastery.com/
Public Sub Select_Case_Multi()

    Dim city As String
    ' Change value to test
    city = "Dublin"
    
    ' Print the name of the airport based on the code
    Select Case city
        Case "Paris", "London", "Dublin"
            Debug.Print "Europe"
        Case "Singapore", "Hanoi"
            Debug.Print "Asia"
        Case Else
            MsgBox "The city is not valid.", vbInformation
    End Select

End Sub

Comparing Upper and Lower Case

We can use Option Compare at the top of the VBA module. This affects how strings are compared within that module.

We can use Binary or Text with Option Compare.

Option Compare Binary
Option Compare Text
  1. Binary means that VBA checks the case of the letters – case sensitive.
  2. Text means that VBA ignores the case of the letters – not case sensitive.

If we set “Option Compare Binary” then the following If and Case statements will evaluate to false.

If we set “Option Compare Text” they will evaluate to true:

city = "Dublin"

' true for "Option Compare Text"
' false for "Option Compare binary"
If city = "DUBLIN" Then
End If

Select Case city
    ' true for "Option Compare Text"
    ' false for "Option Compare binary"
    Case "DUBLIN"
End Select

You can try the following example. Change between Binary and Text and check the results:

' Change between "Binary" and "Text" and compare results
' https://excelmacromastery.com/
Option Compare Binary

Private Sub Select_Case_Multi()

    Dim city As String
    city = "dublin"
    
    ' Print the name of the airport based on the code to the
    ' Immediate Window (Ctrl + G).
    Select Case city
        Case "DUBLIN"
            Debug.Print "Europe"
        Case Else
            Debug.Print "The city is not valid."
    End Select

End Sub

Related Articles

VBA If Statement

VBA MessageBox

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

In this Article

  • Select Case Example
  • Case Statement Syntax
  • Select Case Criteria
    • Exact Match – Numbers
    • Ranges
    • Select Case Is
    • Case Else
  • Select Case – Text & the Like Operator
    • Exact Match – Text
    • Upper and Lower Case
    • Case Like
  • Case – Colon
  • Case Select – And / Or – Multiple Conditions
  • Nested Case Statements
  • Case Statement vs. If Statement
  • VBA Select Case Examples
  • VBA Select Case in Access

In VBA, the Select Case Statement is an alternative to the If-Then statement, allowing you to test if conditions are met, running specific code for each condition. The Select Statement is preferable to the If Statement when there are multiple conditions to process.

Select Case Example

This example prompts the user with a YesNoCancel MessageBox and tests which option the user selected:

Sub Select_Case_Yes_No_Cancel()
    Dim nResult As VbMsgBoxResult
    
    nResult = MsgBox("...", vbYesNoCancel)
    
    Select Case nResult
        Case vbYes
            MsgBox "Yes"
        Case vbNo
            MsgBox "No"
        Case vbCancel
            MsgBox "Cancel"
    End Select
End Sub

vba select case

Below we’ve written out the equivalent using an If Statement instead. You’ll notice that the Case Select Statement involves slightly less typing – this benefit is amplified when testing multiple criteria.

Sub If_Yes_No_Cancel()
    Dim nResult As VbMsgBoxResult
    
    nResult = MsgBox("...", vbYesNoCancel)
    
    If nResult = vbYes Then
        MsgBox "Yes"
    ElseIf nResult = vbNo Then
        MsgBox "No"
    ElseIf nResult = vbCancel Then
        MsgBox "Cancel"
    End If
End Sub

Case Statement Syntax

The Select Case Statement syntax is as follows:

Select Case [Test Expression]
    Case [Condition 1]
        [Action if condition 1 is true]
    Case [Condition 2]
        [Action if condition 2 is true]
    Case [Condition n]
        [Action if condition n is true]
    Case Else
        [Action if none are true]
End Select

Where:

[Test Expression] – Is the value to evaluate. Usually this is a variable.

[Action if condition n is true] – Is just the code to run if the condition is met (just like with an If Statement)

[Condition n] – Is the condition to test. There are a lot of different ways to test conditions. We will discuss them below.

The Case Statement will execute the code for the FIRST condition that is found to be TRUE.  If no condition is met then no code will be executed, unless the Else clause is added.

Select Case Criteria

Select Cases can be used to evaluate both numerical values and text.  First we will discuss how to use Select Cases to evaluate numerical expressions.

Exact Match – Numbers

You can easily test for an exact match with a Case Statement:

Case 10

or add commas to test for exact matches with multiple numbers:

Case 20, 30, 40
Sub ExactMatch_Numbers()
    Dim n As Integer
    n = CInt(InputBox("..."))
    
    Select Case n
        Case 10
            ' If n is 10 Then
        Case 20, 30, 40
            ' If n is 20/30/40 Then
        Case Else
            ' If n is not 10/20/30/40 Then
    End Select
    
End Sub

Ranges

You can test if a number falls within a range like so:

Case 55 To 74

This procedure will generate a letter score for a student based on their numerical score:

Sub Calc_Grade()
Dim Score       As Integer
Dim LetterGrade As String

    Score = InputBox("Enter Student Score")
    
    Select Case Score
        Case 90 To 100
            LetterGrade = "A"            
        Case 80 To 90
            LetterGrade = "B"           
        Case 70 To 80
            LetterGrade = "C"            
        Case 60 To 70
            LetterGrade = "D"            
        Case Else
            LetterGrade = "F"
    End Select
    
    MsgBox "The Student's Grade is: " & LetterGrade
    
End Sub

You can also test ranges with the Case Is

Select Case Is

Case is < 55
  'Do Nothing
Case <= 74
 MsgBox "In Range"

Remember that the Case Statement will only execute code for ONLY the first match.

This procedure will calculate a student’s grade using the Case Is instead of Case To.

Sub Select_Case_Is_Grade()
    Dim Score      As Integer
    Dim LetterGrade As String
    
    Score = InputBox("Enter Student Score")
    
    Select Case Score
        Case Is >= 90
            LetterGrade = "A"            
        Case Is >= 80
            LetterGrade = "B"            
        Case Is >= 70
            LetterGrade = "C"            
        Case Is >= 60
            LetterGrade = "D"            
        Case Else
            LetterGrade = "F"
    End Select
    
    MsgBox "The Student's Grade is: " & LetterGrade
    
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Case Else

You can add “Case Else” to the end of your Case Statement to do something if no conditions are met:

Case Else

See the end of the previous code example to see how Case Else can be used.

Select Case – Text & the Like Operator

So far our Select Case examples have worked only with numbers.  You can also use Select Case statements with text.

Exact Match – Text

You can test if the expression matches an exact phrase like this:

Case "Beets"

Or use commas to test if the expression exactly matches more than one phrase:

Case "Apple", "Banana", "Orange"

Putting it together looks like:

Sub ExactMatch_Food()

Select Case Range("a1").Value
    Case "Beets"
        MsgBox "Vegetable"
    Case "Apple", "Banana", "Orange"
        MsgBox "Fruit"
End Select

End Sub

VBA Programming | Code Generator does work for you!

Upper and Lower Case

By default, VBA is Case Sensitive. This means that VBA considers “Text” different than “text”. To turn case-sensitivity off add Option Compare Text to the top of your module:

Option Compare Text

This example will make the Case Select case-insensitive when working with text:

Option Compare Text

Sub ExactMatch_Food()

Select Case Range("a1").Value
    Case "Beets"
        MsgBox "Vegetable"
    Case "Apple", "Banana", "Orange"
        MsgBox "Fruit"
End Select

End Sub

Case Like

The Like Operator allows you to make inexact comparisons.  If the text matches, Like returns TRUE, if it doesn’t match it returns FALSE.  This makes the Like operator easy to use with If Statements, however it won’t work as easily with Case Statements.

Case Like – A Failed Test

The following code demonstrates that the Like Operator doesn’t work with Select Case:

Sub Select_Case_Like_DoesnotWork()
    Dim word As String
    word = "COCOA"
    
    Select Case word
        Case word Like "*C*C*"
            MsgBox "Good"
        Case Else
            MsgBox "Not Good"
    End Select
End Sub

Case Like – The Correct Way

However, we can add in the TRUE expression to make the Select Statement work with the Like Operator:

Sub Select_Case_Like_CorrectWay()
    Dim word As String
    word = "COCOA"
    
    Select Case True
        Case word Like "*C*C*"
            MsgBox "Good"
        Case Else
            MsgBox "Not Good"
    End Select
End Sub

Case – Colon

When using a Case Statement you can add as many lines of code as you’d like to run with each condition.  However, if you only need to run one line of code. You can use a Colon ( : ) to write everything on the same line.

Here is the same student grade example as before, except using a colon to shorten the code:

Sub Calc_Grade_colon()
Dim Score      As Integer
Dim LetterGrade As String

    Score = InputBox("Enter Student Score")
    
    Select Case Score
        Case 90 To 100: LetterGrade = "A"
        Case 80 To 90: LetterGrade = "B"
        Case 70 To 80: LetterGrade = "C"
        Case 60 To 70: LetterGrade = "D"
        Case Else: LetterGrade = "F"
    End Select
    
    MsgBox "The Student's Grade is: " & LetterGrade
    
End Sub

Case Select – And / Or – Multiple Conditions

You can use the And / Or Operators to test additional criteria along with the Select Case.

In this example we are using a Select Case on the variable ‘age’, but we also want to test sex. So we use the And Operator to perform the more complex test:

Sub NestedSelectCase()
    Dim sex As String
    Dim age As Integer
    
    sex = "male" ' or female
    age = 15
    
    Select Case age
        Case Is < 20 And sex = "male"
            Msgbox "Male under 20"
        Case Is < 20 And sex = "female"
            Msgbox "Female under 20"        
        Case Is >= 20 And sex = "male"
            Msgbox "Male over 20" 
        Case Is >= 20 And sex = "female"
            Msgbox "Female over 20" 
    End Select
End Sub

Nested Case Statements

Just like If Statements, you can nest Case Statements inside each other:

Sub NestedSelectCase()
    Dim sex As String
    Dim age As Integer
    
    sex = "male" ' or female
    age = 15
    
    Select Case age
        Case Is < 20
            Select Case sex
                Case "male"
                    MsgBox "Male under 20"
                Case "female"
                    MsgBox "Female under 20"
            End Select
        Case Is >= 20 And sex = "female"
            Select Case sex
                Case "male"
                    MsgBox "Male over 20"
                Case "female"
                    MsgBox "Female over 20"
            End Select
    End Select
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Case Statement vs. If Statement

The more conditions to test, the more useful the Case Statement is compared to an If Statement. Let’s look at an example.

Here is the code required to test if a worksheet name equals a set of values using an If Statement:

If Name = "Budget" Or Name = "Forecast" Or Name = "Trailing12" Or _
   Name = "Flex" Or Name = "OtherRatios" Or Name = "Comparison" Or _
   Name = "BudReview" Or Name = "P&L_Review" Or Name = "Other" Then
   'Do something
End If

Here is the same code using a Select Statement instead:

Select Case Name
Case "Budget", "Forecast", "Trailing12", "Flex", "OtherRatios", _
     "Comparison", "BudReview", "P&L_Review", "Other"
    'Do Something
End Select

You can see it’s much easier to use a Select Statement in this scenario. It’s significantly less typing, and it’s much easier to read.

VBA Select Case Examples

Ex 1. Case Statement User Defined Function (UDF)

Let’s replicate our grade calculation example above and create a UDF to calculate a student’s score:

Function GetGrade(Score As Integer) As String
    
    Select Case Score
        Case 90 To 100
            GetGrade = "A"            
        Case 80 To 90
            GetGrade = "B"            
        Case 70 To 80
            GetGrade = "C"            
        Case 60 To 70
            GetGrade = "D"           
        Case Else
            GetGrade = "F"
    End Select
    
End Function

Now we can use Function GetGrade in our Excel worksheet to quickly calculate student grades:

vba case select

Ex 2. Test Sheet Name / Loop Case Statement

This code will loop through all worksheets in a workbook, UnProtecting sheets that meet certain criteria:

Sub Case_UnProtectSheet()
    Dim ws As Worksheet
    
    For Each ws In Worksheets
        Select Case ws.Name    'List of all sheets with Ratios
        Case "Budget", "Forecast", "Trailing12", "Flex", "OtherRatios", _
             "Comparison", "BudReview", "P&L_Review", "Other"
            ws.Unprotect
        End Select
    Next ws
    
End Sub

Ex 3. Select Case – Cell Value

This example will test a student’s score in a cell, outputting the letter grade directly to the cell to the right.

Sub TestCellValue()
    Dim cell As Range
    Set cell = Range("C1")

    Select Case cell.Value
    Case 90 To 100
        cell.Offset(0, 1) = "A"
    Case 80 To 90
        cell.Offset(0, 1) = "B"
    Case 70 To 80
        cell.Offset(0, 1) = "C"
    Case 60 To 80
        cell.Offset(0, 1) = "D"
    End Select

End Sub

Ex 4. Select Case – Dates

This Case Select example is a Function that tests which quarter a date fall into.

Sub TestDate ()
 MsgBox GetQuarter(CDate("7/20/2019"))
End Sub

Function GetQuarter(dt As Date) As Integer
    Dim sht As Worksheet

    Select Case dt
        Case CDate("01/01/2019") To CDate("03/31/2019")
            GetQuarter = 1
        Case CDate("04/01/2019") To CDate("06/30/2019")
            GetQuarter = 2
        Case CDate("07/01/2019") To CDate("09/30/2019")
            GetQuarter = 3
        Case CDate("10/01/2019") To CDate("12/31/2019")
            GetQuarter = 4
    End Select
End Function

Because it’s a function, you can use it as a function inside Excel:

vba case select date example

Ex. 5 Check if Number is Odd or Even

This example tests if a number is odd or even.

Sub CheckOddEven()
    Dim n As Integer
    n = InputBox("Enter a number")
    
    Select Case n Mod 2
        Case 0
            MsgBox "The number is even."
        Case 1
            MsgBox "The number is odd."
    End Select
    
End Sub

Ex. 6 Test if Date is on Weekday or Weekend

These examples will test if a date falls on a weekday or a weekend.

Sub CheckWeekDay()
    Dim dt As Date
    dt = CDate("1/1/2020")
    
    Select Case Weekday(dt)
        Case vbMonday
            MsgBox "It's Monday"
        Case vbTuesday
            MsgBox "It's Tuesday"
        Case vbWednesday
            MsgBox "It's Wednesday"
        Case vbThursday
            MsgBox "It's Thursday"
        Case vbFriday
            MsgBox "It's Friday"
        Case vbSaturday
            MsgBox "It's Saturday"
        Case vbSunday
            MsgBox "It's Sunday"
    End Select
End Sub
Sub CheckWeekend()
    Dim dt As Date
    dt = CDate("1/1/2020")
    
    Select Case Weekday(dt)
        Case vbSaturday, vbSunday
            MsgBox "It's a weekend"
        Case Else
            MsgBox "It's not a weekend"
    End Select

End Sub

VBA Select Case in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Sub TestCellValue()
    Dim dbs as Database
    Dim rst as RecordSet
    Set dbs = CurrentDB
    Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
    With rst
       .MoveFirst
       .Edit
       Select Case rst.Fields("City")
       Case "Austin"
           .rst.Fields("TelCode") = "512" 
       Case "Chicago"
           .rst.Fields("TelCode") = "312" 
       Case "New YorK"
           .rst.Fields("TelCode") = "1212" 
       Case "San Fransisco"
           .rst.Fields("TelCode") = "415" 
    End Select
    .Update
   End With
End Sus

VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. 

Some helpful links to get more insights about Macros, VBA in Excel :

  1. Record Macros in Excel.
  2. How to Create a Macro in Excel?

In this article, we are going to discuss how to use Select Case Statement in Excel VBA.

Implementation :

In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. 

The Developer Tab can be enabled easily by a two-step process :

  • Right-click on any of the existing tabs at the top of the Excel window.
  • Now select Customize the Ribbon from the pop-down menu.

  • In the Excel Options Box, check the box Developer to enable it and click on OK.

  • Now, the Developer Tab is visible.

  • Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement.
Developer  -> Visual Basic -> Tools -> Macros
  • Now create a Macro and give any suitable name.

  • This will open the Editor window where can write the code.

Select Case Statement: 

The select case statement is similar to SWITCH-CASE statement in programming languages like C,C++, JAVA, etc. The structure of Select Case in Excel is :

Select Case Expression/Condition
    Case Val_1
    Block of statements when Expression matches Val_1
    Case Val_2
    Block of statements when Expression matches Val_2
    Case Val_3
    Block of statements when Expression matches Val_3
    .
    .
    .
    Case Else
    Block of code when none of the above conditions match
End Select

Val_1, Val_2,... are the values.

Some important keywords used in Select Case in Excel are as follows :

  • Case Is: It is basically used with numbers.

For example Case IS < 70 // Means all numbers less than 70.

  • Case Else: If none of the values of Cases matches with the Expression. It is similar to the default in the SWITCH statement in C/C++.
  •  InputBox: To take input from the user. 
  •  MsgBox: To display output to the user.

Example 1 :

We want to display the grades of students as per the marks obtained by them in an exam. Consider the data set shown below :

Code :

Sub Select_Case_Grade()
'Declaring variables to fetch marks and store the grade
Dim marks As Integer, Grade As String
'Fetching marks from the Excel cell
marks = Range("A2").Value
Select Case marks
    Case Is >= 90
        Grade = "S"
    Case Is >= 80
        Grade = "A"
    Case Is >= 70
        Grade = "B"
    Case Is >= 60
        Grade = "C"
    Case Is >= 50
        Grade = "D"
    Case Is >= 40
        result = "E"
    Case Else
        Grade = "F"
End Select
'Displaying the grade in the Excel cell
Range("B2").Value = Grade
End Sub

Now, change the marks the Grade displayed will be “S”.

You can also write the previous code using range of numbers instead of Case Is

Sub Select_Case_Grade()
'Declaring variables to fetch marks and store the grade
Dim marks As Integer, Grade As String
'Fetching marks from the Excel cell
marks = Range("A2").Value
Select Case marks
    Case 91 To 100
        Grade = "S"
    Case 81 To 90
        Grade = "A"
    Case 71 To 80
        Grade = "B"
    Case 61 To 70
        Grade = "C"
    Case 51 To 60
        Grade = "D"
    Case 40 To 50
        result = "E"
    Case Else
        Grade = "F"
End Select
'Displaying the grade in the Excel cell
Range("B2").Value = Grade
End Sub

Example 2: Consider in a company, employees have to work on a project on the basis of shifts. The company wants to allocate shifts based on odd-even rules and keep age as the deciding criteria. If the age of the employee is odd then he/she has to work in the night shift and if it is even then in the morning shift.

Select Case where the user can input the data in a box.

Sub Select_Case_Allocate()
'Declaring variables to fetch marks and store the grade
Dim Age As Integer
'Asking the user to enter the age
Age = InputBox("Enter Your Age:")
Select Case (Age Mod 2) = 0
    Case True
    MsgBox "You will work in the morning shift"
    Case False
    MsgBox "You will work in the night shift"
End Select
End Sub

Example 3: Let’s create a small calculator which takes two numbers as input and performs addition and multiplication of these numbers.

Code :

Sub Select_Case_Calculator()
'Declaring variables to fetch marks and store the grade
Dim num1 As Integer, mum2 As Integer, operator As String, res As Integer
'Asking the user to enter the numbers and operator to calculate
num1 = InputBox("Enter The First Number:")
num2 = InputBox("Enter The Second Number:")
operator = InputBox("Enter The Operator Name(Sum,Mul):")
Select Case operator
    Case "Sum"
    res = num1 + num2
    MsgBox ("The result is :" & res)
    Case "Mul"
    res = num1 * num2
    MsgBox ("The result is :" & res)
    Case Else
    MsgBox "Please Enter a Valid Operator"
End Select
End Sub

We can modify the above code and use multiple conditions in the case. For example, the user can input the string Sum as “SUM” or “sum” as the Excel dialog box is case-sensitive.

Sub Select_Case_Calculator()
'Declaring variables to fetch marks and store the grade
Dim num1 As Integer, mum2 As Integer, operator As String, res As Integer
'Asking the user to enter the numbers
num1 = InputBox("Enter The First Number:")
num2 = InputBox("Enter The Second Number:")
operator = InputBox("Enter The Operator Name(Sum,Mul):")
Select Case operator
    Case "Sum", "SUM", "sum", "SUm", "SuM", "suM", "sUm"
    res = num1 + num2
    MsgBox ("The result is :" & res)
    Case "Mul", "mul", "MUL", "MuL", "muL", "mUl", "MUl"
    res = num1 * num2
    MsgBox ("The result is :" & res)
    Case Else
    MsgBox "Please Enter a Valid Operator"
End Select
End Sub

Example 4: Let’s see an example using a nested Select Case.

Consider a company that has a policy department-wise regarding the total number of leaves an employee can take in a single year. Now, there are multiple departments and there are female as well as male employees and everyone has different policies for applying for leave. So, a nested Select Case is used to build the problem statement where users can enter the details of department and gender to check the maximum number of days they can take leave in a year.

Sub Select_Case_Empleave()
'Declaring variables to fetch Department and gender of employee
Dim Department As String, sex As String
'Asking the user to enter the details
Department = InputBox("Enter Your Department:")
sex = InputBox("Enter Your Gender (Male,Female):")
Select Case Department
    Case "HR"
    Select Case sex
        Case "Male"
        MsgBox ("You can take maximum 10 days leave in an year")
        Case "Female"
        MsgBox ("You can take maximum 20 days leave in an year")
        Case Else
        MsgBox ("Invalid Gender")
    End Select
    Case "IT"
    Select Case sex
        Case "Male"
        MsgBox ("You can take maximum 15 days leave in an year")
        Case "Female"
        MsgBox ("You can take maximum 25 days leave in an year")
        Case Else
        MsgBox ("Invalid Gender")
    End Select
Case Else

Понравилась статья? Поделить с друзьями:
  • Excel любой символ в ячейке
  • Excel любой символ в формуле если
  • Excel любое число в ячейке
  • Excel любое число в формуле
  • Excel любое значение в формуле excel