Select case with if vba excel

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

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

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

Содержание

  1. Оператор Select Case
  2. Синтаксис
  3. Замечания
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. VBA Select Case Statement – Explained
  8. Syntax of VBA Select Case Statement
  9. Examples of Select-Case in VBA
  10. Subscribe and be a part of our 15,000+ member family!
  11. VBA Excel. Оператор Select Case (синтаксис, примеры)
  12. Описание оператора Select Case
  13. Синтаксис оператора Select Case
  14. Компоненты оператора Select Case
  15. Примеры использования в VBA Excel
  16. Пример 1
  17. VBA Select Case
  18. Select Case Statement of Excel VBA
  19. Syntax of the Select Case Statement of Excel VBA
  20. How to use the Select Case Statement of Excel VBA?
  21. VBA Select Case Examples
  22. Example #1–“Expression for Testing” is Entered Directly
  23. Example #2–“Expression for Testing” is Compared with a Range of Values Using the “To” Keyword
  24. Example #3–“Expression for Testing” is Compared with Numbers Using the “Is” Keyword
  25. Example #4–“Expression for Testing” is Entered in a Cell and Evaluated by the Command Button
  26. Example #5–“Expression for Testing” is Divided by 2 with the MOD Operator of VBA
  27. Example #6–Nested Select Case Statements Where “Expression for Testing” is the Current Date
  28. The Key Points Related to the Select Case Statement of Excel VBA
  29. Frequently Asked Questions
  30. Recommended Articles

Оператор Select Case

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

Синтаксис

Выборвыражения для тестирования варианта
[ Caseexpressionlist-n [ statements-n ]]
[ Case Else [ elsestatements ]]
End Select

Синтаксис оператора Select Case состоит из следующих частей:

Part Описание
выражение testexpression Обязательно. Любое числовое выражение или строковое выражение.
expressionlist-n Обязательный параметр, если используется оператор Case.

Разделенный список одной или нескольких из следующих форм: expression, expressionToexpression, Iscomparisonoperatorexpression.

Ключевое словоTo задает диапазон значений. Если вы используете ключевое слово To, то наименьшее значение должно быть указано до To.

Используйте ключевое слово Is с операторами сравнения (кроме Is и Like) для указания диапазона значений. Если этот параметр не указан, автоматически вставляется ключевое слово Is.

statements-n Необязательный параметр. Одна или несколько инструкций, выполняемых, если выражение testexpression соответствует любой части expressionlist-n.
elsestatements Необязательный параметр. Один или несколько операторов, которые выполняются, если testexpression не соответствует какому-либо из выражений Case.

Замечания

Если выражение testexpression соответствует любому выражениюсписка выраженийcase, операторы, следующие за этим предложением Case, выполняются до следующего предложения Case или до последнего предложения до end select. Затем контроль передается оператору после End Select. Если testexpression совпадает с выражением expressionlist в нескольких предложениях Case, выполняются только операторы после первого совпадения.

Предложение Case Else используется для указания того, что выражения elsestatements выполняются, если не обнаружено совпадение между testexpression и expressionlist в других предложениях Case. Хотя это необязательно, рекомендуется использовать оператор Case Else в блоке Select Case для обработки непредвиденных значений testexpression. Если список выраженийcase не соответствует testexpression и оператор Case Else отсутствует, выполнение продолжается в инструкции End Select.

Используйте несколько выражений или диапазонов в каждом предложении Case . Например, допустима следующая строка.

Оператор сравнения Is — не то же самое, что ключевое слово Is, используемое в операторе Select Case.

Вы также можете указать диапазоны и несколько выражений для строк символов. В следующем примере case сопоставляет строки, которые точно равны , строки, которые находятся everything между nuts и soup в алфавитном порядке, и текущее значение TestItem :

Операторы Select Case могут быть вложенными. Каждый вложенный оператор Select Case должен иметь соответствующую инструкцию End Select .

Пример

В этом примере оператор Select Case используется для оценки значения переменной. Второе предложение Case содержит значение оцениваемой переменной, поэтому выполняется только связанный с ним оператор.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Select Case Statement – Explained

In our previous posts, we have talked about Excel If Statement and Excel Nested If’s, and in today’s post we will discuss VBA select case statement. VBA Select Case can be used instead of complex Excel Nested If statements. This makes the VBA code faster to execute and easier to understand.

Select-Case statement (also called as Switch Case in some languages) checks a variable or an expression for different cases (values). If anyone of the case becomes true then only that case is executed and the program ignores all other cases.

If you remember in the last post we talked about, “how you can change the program flow with VBA MsgBox and case statements”.

Syntax of VBA Select Case Statement

The Syntax is as under:

Here, ‘ Condition ’ refers to the variable or the expression that is to be tested and based on which any one of the code segments will be executed.

‘value_1’, ‘value_2’ and ‘value_3’ are the possible outcomes of the ‘Condition’. Whenever anyone of these values matches the ‘Condition’ then its corresponding Case block will execute.

‘Else’ is a kind of default case value, which will only execute when all the above Case statements result is False. ‘Else’ case is optional but generally, it is considered a good practice to use it.

Examples of Select-Case in VBA

Now let’s move on to some practical examples of case Statements.

Example 1: Select Case Statement with an Expression.

In the below example, we have supplied a condition (i.e. a=b) to the Select Case statement. If this is True then the ‘Case True’ block will be executed and if it is False then the ‘Case False’ block will execute.

Note: In this code, the InputBox function is used for getting values from the user.

Example 2: Case statement to check Text Strings

In this example, we will compare text strings in the Case statements. If a match is found then the corresponding case block will execute otherwise the ‘Case Else’ block will execute.

Example 3: Case statement to check numbers

In the below example we will check if the number entered by the user is less than or greater than 5.

Note: You can use the IS keyword with the Case Statement to compare values.

Example 4: Select a Case statement to check multiple conditions inside a single case.

In this example, we will ask the user to enter any number from 1-10. And then we will check if the number is even or odd by using multiple conditions in the case statement. Notice here I have used a “,” (comma) to compare multiple conditions in a single case.

Note: I know that there are easier methods to check if a number is even or odd, but I have used this example only for explaining how you can check multiple conditions inside a single case statement.

Example 5: Case statement to check a continuous range as a condition.

Here we will test a continuous range as a condition. We will ask the user to enter any number between 1-10, if the number is between 1 to 5 (including both 1 and 5) then ‘Case 1 To 5’ will be ‘True’, if the number entered by the user is between 6 and 10 (including both 6 and 10) then ‘Case 6 To 10’ will be ‘True’, if both the previous cases are ‘False’ then ‘Case Else’ will be executed.

So, this was all about VBA Select Case Statement. Feel free to share your thoughts about this topic.

Subscribe and be a part of our 15,000+ member family!

Now subscribe to Excel Trick and get a free copy of our ebook «200+ Excel Shortcuts» (printable format) to catapult your productivity.

Источник

VBA Excel. Оператор Select Case (синтаксис, примеры)

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

Описание оператора Select Case

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

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

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

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

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

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

Пример 1

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

Источник

VBA Select Case

Select Case Statement of Excel VBA

The Select Case VBA statement compares an expression with multiple Case statements containing conditions. If a match is found in any of the Case statements, the condition is said to be true. Further, if a condition is true, its corresponding code is executed and no more Case statements are tested. However, if a match is not found in any of the Case statements, the conditions are said to be false. In this case, the code of the Case Else statement is executed.

For example, an employee is asked to rate the work-life balance of his organization on a scale of 10. Further, his input will be compared with the following three conditions (or possible outcomes):

  • If the input is between 1 and 3 (both inclusive), display the message “the work-life balance is poor.”
  • If the input is between 4 and 6 (both inclusive), display the message “the work-life balance is reasonable.”
  • If the input is between 7 and 10 (both inclusive), display the message “the work-life balance is healthy.”

The message of only that condition will display, which matches the input entered by the employee. Note that the expression can either be entered directly in a Select Case structure or collected from the user as an input.

The purpose of using the Select Case statement in VBA is to execute different codes based on the fulfillment or non-fulfillment of different conditions. The Select Case statement is used to evaluate (or test) three or more conditions. It is a substitute for the If Then Else statement of VBA and the nested IF statement of Excel.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Select Case (wallstreetmojo.com)

Syntax of the Select Case Statement of Excel VBA

The Select Case statement in VBA is similar to the Switch Case statement used in programming languages like Java, C#, PHP, etc. The syntax of the Select Case statement of Excel VBA is given as follows:

The Select Case statement of Excel VBA accepts the following arguments:

  • Expression for testing: This is a single expression that is to be compared with the different Cases. It can either be a numeric or textual expression. So, it can evaluate to a character, integer, Boolean, object, string, etc.
  • List of expressions: This is the list of expressions (called Case statements) against which the “expression for testing” is compared. Excel VBA looks for an exact match within these Case statements. These Case statements consist of one or more possible outcomes (values or conditions) that may or may not match the “expression for testing.” If there are multiple expressions (or values) within a single Case, they must be separated by commas. The following keywords can be used in Case statements:
    • The To keyword should be used when a range of values needs to be specified in a Case statement. The value preceding the To keyword should be less than or equal to the value succeeding this keyword.
    • The Is keyword should be used when a logical operatorLogical Operators In ExcelLogical operators in excel are also known as the comparison operators and they are used to compare two or more values, the return output given by these operators are either true or false, we get true value when the conditions match the criteria and false as a result when the conditions do not match the criteria.read more (=, <>, , =) needs to be entered in a Case statement. This keyword should be inserted before the logical operator.
  • Statements: This is one or more codes succeeding the “list of expressions.” Only that code is executed for which the “expression for testing” matches the “list of expressions.”
  • Case Else statement: This consists of one or more codes (or statements), which are executed when all the Case statements (or list of expressions) are false.
  • End Select: It closes the Select Case structure. Every Select Case statement must necessarily have an End Select statement.

The “expression for testing,” “list of expressions,” and End Select clauses are required in a Select Case construction. However, the “statements” and Case Else statements are optional in the given syntax.

Note 1: In a Select Case statement in VBA, each Case statement is compared with the “expression for testing.” Once a condition is met (or the Case statement is matched), no further Case statements are tested. However, if a condition is false (or the Case statement does not match), the next Case statement is tested.

The testing of Case statements (or conditions) continues till one of the specified conditions is met or till the Case Else or the End Select statement. If none of the tested conditions is true and there is no Case Else statement, control passes to the End Select statement.

Note 2: If the “expression for testing” matches more than one Case statement, only the code of the first such match is executed.

How to use the Select Case Statement of Excel VBA?

The steps to use the Select Case statement of VBA are listed as follows:

  1. Create a command button and place it in the Excel worksheet. When the command button is clicked, a macroExcel MacroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.read more runs. The running of the macro performs an action.
  2. Right-click the command button and choose the option “view code.” The Visual Basic Editor opens.
  3. Enter the code between the CommandButton function and End Sub.
  4. Debug and compile the code to identify the syntax errors.
  5. Change the input values to observe the different outputs.

Note 1: The user-defined functions (UDF) are customized functions that cater to the specific needs of the user.

Note 2: Every time the input is changed (in point e), the “expression for testing” changes. As a result, the conditions that match this expression change. Hence, different codes are executed each time the input values change.

VBA Select Case Examples

Example #1–“Expression for Testing” is Entered Directly

In the following code, the “expression for testing” is A=20 and the Case statements are 10, 20, 30, and 40. There is also a Case Else statement in this code.

On running the preceding code, the following output is obtained.

Explanation: The expression A=20 is compared with the four Case statements 10, 20, 30, and 40. A match is found in the second Case statement (Case 20). Consequently, the message of the second Case statement is displayed, which is “the second Case is matched.”

Had the expression not matched with any of the Case statements, the message of the Case Else statement would have been displayed.

Note: The MsgBox function of VBA displays a dialog box containing a customized message.

Example #2–“Expression for Testing” is Compared with a Range of Values Using the “To” Keyword

In the following code, the “expression for testing” is collected from the user with the help of the InputBox function of VBA. There are four Case statements, namely Case 1 To 36, Case 37 To 55, Case 56 To 80, and Case 81 To 100. There is also a Case Else statement in the code.

On running the preceding code, the user is asked for input. Assume that the user enters 90. So, the following output is obtained.

Explanation: The Case statements of the preceding code contain a range of values. Notice that in the code, each number preceding the To keyword is smaller than the number succeeding this keyword.

The “expression for testing” is entered as 90 by the user. This expression matches the fourth Case statement (Case 81 to 100). So, the code in this Case statement is executed. Hence, the message “A grade” is returned by VBA. This output is displayed in a dialog box due to the usage of the MsgBox function in the code.

Both numbers (preceding and succeeding the To keyword) of the range are inclusive. So, had the user entered 81, it would have again matched with the fourth Case statement. However, had a number greater than 100 been entered, the output would have been “out of range.” This message is defined in the Case Else statement of the code.

Note: The InputBox function collects the input from the user through a dialog box. The message shown in this dialog box is the same as that entered in the InputBox function of the code.

Example #3–“Expression for Testing” is Compared with Numbers Using the “Is” Keyword

In the following code, the “expression for testing” is collected from the user. There are two Case statements, namely Case Is = 200. There is no Case Else statement in the code.

On running the preceding code, a dialog box containing the message “please enter a number” is displayed. Assume that the user enters 200. So, the following output is displayed.

Explanation: Observe that the two logical operators ( =) in the code are preceded by the “Is” keyword. Had this keyword not been supplied, VBA would have automatically inserted it before the logical operators.

The “expression for testing” is entered by the user as 200. This expression is compared with the two Case statements of the preceding code. A match is found in the second Case statement. This is because 200 is not greater than but is equal to 200.

Notice that there is no Case Else statement in the preceding code. This is because whatever number the user enters, it falls within either of the two Case statements. So, one of the two Case statements will always be true. Hence, the Case Else statement is not required as it runs only when all Case statements evaluate to false.

Example #4–“Expression for Testing” is Entered in a Cell and Evaluated by the Command Button

In the following code, the “expression for testing” is taken from cell A1 of the Excel worksheet. There are three Case statements and one Case Else statement.

Further, a command button has been created in the worksheet with the help of ActiveX controls. The input entered in cell A1, the command button, and the output obtained in cell B1 are shown in the following image.

Explanation: The preceding code is executed by clicking the command button of the Excel worksheet. Notice that multiple expressions of each Case statement are separated by commas (like “Red”, “Green”, “Yellow”).

The “expression for testing” is entered as “pink” in cell A1. This expression matches none of the three Case statements specified in the code. Consequently, the code of the Case Else statement is executed. So, the output in cell B1 is 4.

Had the user entered a color (in cell A1) specified in any of the three Case statements, the corresponding code would have run. For instance, had the user entered “White” in cell A1 (without the double quotes and with “W” capital), the output in cell B1 would have been 2.

Hence, a change in the input of cell A1 causes the output of cell B1 to change.

Example #5–“Expression for Testing” is Divided by 2 with the MOD Operator of VBA

In the following code, the “expression for testing” is collected from the user. There are two Case statements, namely Case True and Case False. The Case Else statement is not there in the code.

On running the preceding code, a dialog box with the message “enter the number” is displayed. Assume that the user enters 10. The output obtained is shown in the following image.

Explanation: The “expression for testing” entered by the user is 10. This expression is divided by 2 with the help of the MOD operator MOD Operator VBA MOD is the same as the application in mathematics. When a number is divided by its divisor, this function gives us the remainder from the division. However, it is not a function in VBA; rather it is an operator. read more . If the remainder is equal to zero, the number is divisible by 2. Such a number is even. If the remainder is not equal to zero, the number is not divisible by 2 and is odd.

Since 10 is divisible by 2, the code of the Case True statement is executed. Hence, the output is the message “the number is even.” Notice that a Case Else statement is not required in the preceding code. This is because either of the two Case statements will be true at all times.

Note: The MOD operator of VBA divides one number by the other and returns the remainder as the output.

Example #6–Nested Select Case Statements Where “Expression for Testing” is the Current Date

In the following code, the “expression for testing” is the current date. There are two Select Case statements [Select Case Weekday (Now) and Case 1,7], one Case Statement (Case 1), and two Case Else statements.

On running the preceding code, the output obtained is shown in the following image.

Explanation: The inner Select Case statement (Case 1, 7) is the Case statement of the outer Select Case statement [Select Case Weekday (Now)]. The outer Select Case statement checks whether the current date is a weekday, Saturday or Sunday.

When the NOW VBA function NOW VBA Function NOW is a date and time function in VBA which is used to get the current system date and time. VBA Now function does not takes any arguments and the return output for this function is date. read more is enclosed within the VBA WEEKDAY function VBA WEEKDAY Function Weekday in VBA is a date and time function to identify the weekday of a given date provided as an input. This function returns an integer value from 1 to 7 range. There is an optional argument provided to this function which is the first day of the week. read more , the latter returns a day of the week that corresponds with the current date. If the output of the WEEKDAY function is 1, the message to be displayed is “today is Sunday.” If the output of the WEEKDAY function is 7, the message to be displayed is “today is Saturday.” This is because, in the preceding code, VBA considers 1 and 7 as Sunday and Saturday respectively.

The message “today is a weekday” will be returned when the output of the WEEKDAY function is other than 1 and 7. So, the second Case Else statement is executed when Case 1 (today is Sunday) and the first Case Else statements (today is Saturday) are false.

Since this article has been created on a weekday, the output of the Select Case statement is “today is a weekday.”

Note 1: The NOW function of VBA returns the current date and time. This function does not take any arguments. The WEEKDAY function of VBA returns the day of the week corresponding to the specified date.

Note 2: Every nested Select Case statement should necessarily contain a matching End Select statement.

The important points related to the Select Case statement of VBA are listed as follows:

  • The Is keyword used in the Case statement and Case Else statement is different from the Is operator of VBA.
  • The codes of the Select Case statement of VBA can run successfully if macros have been enabled.
  • The “expression for testing” entered in the dialog box should be in accordance with the message of the InputBox function of VBA.

Frequently Asked Questions

The Select Case statement is used to compare an expression with multiple Case statements. If a Case statement matches the expression, the corresponding code is executed. However, if a Case statement does not match the expression, the next Case statement is evaluated.

The evaluation of Case statements continues till a match is found or till the Case Else or End Select statement. Once a match is found in any of the Case statements, no further Case statements are tested. The Case Else statement is optional and its code is executed when none of the Case statements is true.

Note: For details related to the working of the VBA Select Case statement, refer to the examples of this article.

The steps to write the Select Case statement of Excel VBA are listed as follows:

a. Specify a single expression that needs to be compared with multiple Case statements. This expression can be numeric or textual. Note that the expression is evaluated only once and is stated at the beginning of the Select Case structure.
b. Specify the Case statements. Each Case statement should consist of one or more conditions (or possible outcomes) followed by a code. For stating multiple conditions within the same Case statements, use the comma as the separator.
c. Specify the Case Else statement. The code of this statement will be executed if none of the Case statements match the expression. Though it is optional to specify the Case Else statement, it is recommended to be included in the Select Case structure.
d. State the End Select statement. This statement is necessarily required as it terminates the Select Case structure. If no Case statement matches the expression and there is no Case Else statement, control passes to the End Select statement.

Note 1: If the expression (in point a) is to be collected as an input from the user, a customized message must be stated within the InputBox function of VBA.

Note 2: For more details related to the writing of the VBA Select Case statement, refer to the codes of the examples and their explanations given in this article.

The differences between the Select Case and If Then Else statements of Excel VBA are listed as follows:

a. The Select Case statement evaluates a single expression at a time, while the If Then Else statement can evaluate multiple expressions simultaneously.
b. The Select Case statement checks one expression for multiple possible outcomes, while the If Then Else statement checks multiple expressions for multiple possible outcomes.
c. In a Select Case statement, any number of Case statements can be included without impacting the readability of the code. In contrast, a lot of conditions tend to make the If Then Else statement unreadable.
d. It is easy to write, edit, and make changes to the Select Case statement. On the other hand, it is difficult to write, identify errors, and make changes to the If Then Else statement.

In both, Select Case and If Then Else statements, a code is executed depending on whether a condition is met or not. So, based on the requirement and convenience, one can choose either of the two statements.

Recommended Articles

This has been a guide to the Excel VBA Select Case statement. Here we discuss how to use the Excel VBA Select Case statements with certain keywords (like Is, To) along with examples and a downloadable Excel template. Take a look at the following Excel VBA articles–

Источник

Excel VBA has the IF Then Else construct that you can use to analyze multiple conditions and execute codes based on these conditions.

Another similar construct that allows you to check for multiple conditions is the SELECT CASE statement.

Select Case is useful when you have three or more conditions that you want to check. You can also use this with two conditions (but I feel If Then Else is easier to use in those cases).

A simple example where the Select Case statement is useful when you want to get the grade of a student based on the marks he/she has scored (covered as an example later in this tutorial).

Note: All the example codes covered in this tutorial are meant to be placed in a module in VBA.

Select Case Syntax

Below is the syntax of Select Case in Excel VBA:

Select Case Test_Expression

Case Value_1
Code Block when Test_Expression = Value_1

Case Value_2
Code Block when Test_Expression = Value_2

Case Value_3
Code Block when Test_Expression = Value_3

Case Else
Code Block when none of the case conditions are met

End Select
  • Test_Expression: This is the expression whose value we analyze by using different cases (explained better with the examples below).
  • Condition_1, Condition_2,…: These are the conditions on which the text expression is tested. If it meets the condition, then the code block for the given condition is executed.

For every Select Case statement that you use, you need to use the End Select statement.

Note: As soon as a condition is met, VBA exits the select case construct. So if you have five conditions, and the second condition is met, VBA would exit Select Case – and the rest of the conditions will not be tested.

Select Case Examples

Now to better understand how to use Select Case statement in VBA, let’s go through a few examples.

Note that most of the examples in this tutorial are meant to explain the concept. These may or may not be the best way to get the work done.

Let’s start with a simple example of see how Select Case allows us to check for conditions.

Example 1 – Check the Numbers

In the below example, the code asks the user to enter any number between 1 and 5, and then shows a message box with the number the user entered.

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number between 1 and 5")

Select Case UserInput

Case 1
MsgBox "You entered 1"

Case 2
MsgBox "You entered 2"

Case 3
MsgBox "You entered 3"

Case 4
MsgBox "You entered 4"

Case 5
MsgBox "You entered 5"

End Select
End Sub

Note that this code is far from useful and is not even foolproof. For example, if you enter 6 or any string, it would do nothing. But as I mentioned, my intent here is to showcase how Select Case works.

Example 2 – Using Select Case with IS Condition

You can use an IS condition with the Select Case construct to check for the value of numbers.

The below code checks whether the input number is greater than 100 or not.

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number")

Select Case UserInput

Case Is < 100
MsgBox "You entered a number less than 100"

Case Is >= 100
MsgBox "You entered a number more than (or equal to) 100"

End Select
End Sub

Example 3 – Using Case Else to Catch All

In the above example, I used two conditions (less than 100 or greater than or equal to 100).

Instead of the second case with a condition, you can also use Case Else.

Case Else acts as a catch-all and anything which doesn’t fall into any of the previous cases is treated by the Case Else.

Below is an example code where I have used Case Else:

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number")

Select Case UserInput

Case Is < 100
MsgBox "You entered a number less than 100"

Case Else
MsgBox "You entered a number more than (or equal to) 100"

End Select
End Sub

Example 4 – Using a Range of Numbers

In Select Case, you can also check for a range of numbers.

The below code asks for an input and shows a message box based on the value.

Sub CheckNumber()
Dim UserInput As Integer
UserInput = InputBox("Please enter a number between 1 and 100")

Select Case UserInput

Case 1 To 25
MsgBox "You entered a number less than 25"

Case 26 To 50
MsgBox "You entered a number between 26 and 50"

Case 51 To 75
MsgBox "You entered a number between 51 and 75"

Case 75 To 100
MsgBox "You entered a number more than 75"

End Select
End Sub

Example 5 – Get the Grade based on the Marks Scored

So far we have seen basic examples (which are not really useful in the practical world).

Here is an example which is closer to a real-world example where you can use Select Case in Excel VBA.

The following code will give you the grade a student gets based on the marks in an exam.

Sub Grade()
Dim StudentMarks As Integer
Dim FinalGrade As String
StudentMarks = InputBox("Enter Marks")

Select Case StudentMarks

Case Is < 33
FinalGrade = "F"

Case 33 To 50
FinalGrade = "E"

Case 51 To 60
FinalGrade = "D"

Case 60 To 70
FinalGrade = "C"

Case 70 To 90
FinalGrade = "B"

Case 90 To 100
FinalGrade = "A"

End Select
MsgBox "The Grade is " & FinalGrade

End Sub

The above code asks the user for the marks and based on it, shows a message box with the final grade.

In the above code, I have specified all the conditions – for marks 0 – 100.

Another way to use Select Case is to use a Case Else at the end. This is useful when you have accounted for all the conditions and then specify what to do when none of the conditions is met.

The below code is a variation of the Grade code with a minor change. In the end, it has a Case else statement, which will be executed when none of the above conditions are true.

Sub CheckOddEven()
Dim StudentMarks As Integer
Dim FinalGrade As String
StudentMarks = InputBox("Enter Marks")
Select Case StudentMarks
Case Is < 33
FinalGrade = "F"

Case 33 To 50
FinalGrade = "E"

Case 51 To 60
FinalGrade = "D"

Case 60 To 70
FinalGrade = "C"

Case 70 To 90
FinalGrade = "B"

Case Else
FinalGrade = "A"

End Select
MsgBox "The Grade is " & FinalGrade

End Sub

Example 6 – Creating a Custom Function (UDF) using Select Case

In the above example, the code asked the user for the marks input.

You can also create a custom function (User Defined Function) that can be used just like any regular worksheet function, and which will return the grade of the students.

Below is the code that will create the custom formula:

Function GetGrade(StudentMarks As Integer)
Dim FinalGrade As String

Select Case StudentMarks

Case Is < 33
FinalGrade = "F"

Case 33 To 50
FinalGrade = "E"

Case 51 To 60
FinalGrade = "D"

Case 60 To 70
FinalGrade = "C"

Case 70 To 90
FinalGrade = "B"

Case Else
FinalGrade = "A"

End Select
GetGrade = FinalGrade

End Function

Once you have this code in the module, you can use the function GetGrade in the worksheet as shown below.

Select Case Statement in Excel VBA - Get Grade Custom Function

Example 7 – Check ODD / EVEN with Select Case

Below is an example code where I check whether the number in cell A1 is odd or even.

Sub CheckOddEven()
CheckValue = Range("A1").Value

Select Case (CheckValue Mod 2) = 0

Case True
MsgBox "The number is even"

Case False
MsgBox "The number is odd"

End Select
End Sub

Example 8 – Checking for Weekday/Weekend (Multiple Conditions)

You can also use Select Case to check for multiple values in the same case.

For example, the below code uses the current date to show whether today is a weekday or weekend (where weekend days are Saturday and  Sunday)

Sub CheckWeekday()
Select Case Weekday(Now)

Case 1, 7
MsgBox "Today is a Weekend"

Case Else
MsgBox "Today is a Weekday"

End Select
End Sub

In the above code, we check for two conditions (1 and 7) in the same case.

Note: Weekday function returns 1 for Sunday and 7 for Saturday.

Example 9 – Nested Select Case Statements

You can also nest one Select Case statement within other.

Below is a code that checks whether a day is a weekday or a weekend, and if it’s a weekend, then it will display whether it’s a Saturday or a Sunday.

Sub CheckWeekday()
Select Case Weekday(Now)

Case 1, 7
   Select Case Weekday(Now)
   Case 1
      MsgBox "Today is Sunday"
   Case Else
      MsgBox "Today is Saturday"
  End Select

Case Else
MsgBox "Today is a Weekday"
End Select
End Sub

In the above code, I have nested the Select Case to check whether the weekend is a Saturday or a Sunday.

Note: The example shown above is to explain the concept. This is not the best or the most practical way to find out weekday/weekend.

Example 10 – Checking Text String with Select Case

You can check specific strings using Select Case and then execute code based on it.

In the example code below, it asks the user to enter their department name and shows the name of the person they should connect with for onboarding.

Sub OnboardConnect()
Dim Department As String
Department = InputBox("Enter Your Department Name")

Select Case Department

Case "Marketing"
MsgBox "Please connect with Bob Raines for Onboarding"

Case "Finance"
MsgBox "Please connect with Patricia Cruz for Onboarding"

Case "HR"
MsgBox "Please connect with Oliver Rand for Onboarding"

Case "Admin"
MsgBox "Please connect with Helen Hume for Onboarding"

Case Else
MsgBox "Please connect with Tony Randall for Onboarding"

End Select
End Sub

Hope all the examples above were helpful in understanding the concept and application of Select Case in Excel VBA.

You May Also Like the Following VBA Tutorials:

  • Excel VBA Loops – For Next, Do While, Do Until, For Each.
  • For Next Loop in Excel VBA.
  • How to Record a Macro in Excel.

Select Case Statement of Excel VBA

The Select Case VBA statement compares an expression with multiple Case statements containing conditions. If a match is found in any of the Case statements, the condition is said to be true. Further, if a condition is true, its corresponding code is executed and no more Case statements are tested. However, if a match is not found in any of the Case statements, the conditions are said to be false. In this case, the code of the Case Else statement is executed.

For example, an employee is asked to rate the work-life balance of his organization on a scale of 10. Further, his input will be compared with the following three conditions (or possible outcomes):

  • If the input is between 1 and 3 (both inclusive), display the message “the work-life balance is poor.”
  • If the input is between 4 and 6 (both inclusive), display the message “the work-life balance is reasonable.”
  • If the input is between 7 and 10 (both inclusive), display the message “the work-life balance is healthy.”

The message of only that condition will display, which matches the input entered by the employee. Note that the expression can either be entered directly in a Select Case structure or collected from the user as an input.

The purpose of using the Select Case statement in VBA is to execute different codes based on the fulfillment or non-fulfillment of different conditions. The Select Case statement is used to evaluate (or test) three or more conditions. It is a substitute for the If Then Else statement of VBA and the nested IF statement of Excel.

Table of contents
  • Select Case Statement of Excel VBA
    • Syntax of the Select Case Statement of Excel VBA
    • How to use the Select Case Statement of Excel VBA?
    • VBA Select Case Examples
      • Example #1–“Expression for Testing” is Entered Directly
      • Example #2–“Expression for Testing” is Compared with a Range of Values Using the “To” Keyword
      • Example #3–“Expression for Testing” is Compared with Numbers Using the “Is” Keyword
      • Example #4–“Expression for Testing” is Entered in a Cell and Evaluated by the Command Button
      • Example #5–“Expression for Testing” is Divided by 2 with the MOD Operator of VBA
      • Example #6–Nested Select Case Statements Where “Expression for Testing” is the Current Date
    • The Key Points Related to the Select Case Statement of Excel VBA
    • Frequently Asked Questions
    • Recommended Articles

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Select Case (wallstreetmojo.com)

Syntax of the Select Case Statement of Excel VBA

The Select Case statement in VBA is similar to the Switch Case statement used in programming languages like Java, C#, PHP, etc. The syntax of the Select Case statement of Excel VBA is given as follows:

Select [Case]  Expression for testing
  
[Case] List of Expression Statements (Case 1, Case 2, Case 3 and so on...)

Case Else (Else Statements)

End Select
End Sub

The Select Case statement of Excel VBA accepts the following arguments:

  • Expression for testing: This is a single expression that is to be compared with the different Cases. It can either be a numeric or textual expression. So, it can evaluate to a character, integer, Boolean, object, string, etc.
  • List of expressions: This is the list of expressions (called Case statements) against which the “expression for testing” is compared. Excel VBA looks for an exact match within these Case statements. These Case statements consist of one or more possible outcomes (values or conditions) that may or may not match the “expression for testing.” If there are multiple expressions (or values) within a single Case, they must be separated by commas. The following keywords can be used in Case statements:
    • The To keyword should be used when a range of values needs to be specified in a Case statement. The value preceding the To keyword should be less than or equal to the value succeeding this keyword.
    • The Is keyword should be used when a logical operatorLogical operators in excel are also known as the comparison operators and they are used to compare two or more values, the return output given by these operators are either true or false, we get true value when the conditions match the criteria and false as a result when the conditions do not match the criteria.read more (=, <>, <, >, <= or >=) needs to be entered in a Case statement. This keyword should be inserted before the logical operator.
  • Statements: This is one or more codes succeeding the “list of expressions.” Only that code is executed for which the “expression for testing” matches the “list of expressions.”
  • Case Else statement: This consists of one or more codes (or statements), which are executed when all the Case statements (or list of expressions) are false.
  • End Select: It closes the Select Case structure. Every Select Case statement must necessarily have an End Select statement.

The “expression for testing,” “list of expressions,” and End Select clauses are required in a Select Case construction. However, the “statements” and Case Else statements are optional in the given syntax.

Note 1: In a Select Case statement in VBA, each Case statement is compared with the “expression for testing.” Once a condition is met (or the Case statement is matched), no further Case statements are tested. However, if a condition is false (or the Case statement does not match), the next Case statement is tested.

The testing of Case statements (or conditions) continues till one of the specified conditions is met or till the Case Else or the End Select statement. If none of the tested conditions is true and there is no Case Else statement, control passes to the End Select statement.

Note 2: If the “expression for testing” matches more than one Case statement, only the code of the first such match is executed.

How to use the Select Case Statement of Excel VBA?

The Select Case statement is a feature of Excel VBA. One can access VBA from the “visual basic” option of the Developer tab of ExcelEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more. In this tab, the user-defined functions (UDF) and their codes can be created.

The Select Case statement of VBA should be used in place of the nested IF statementIn Excel, multiple IF conditions are IF statements that are contained within another IF statement. They are used to test multiple conditions at the same time and return distinct values. Additional IF statements can be included in the ‘value if true’ and ‘value if false’ arguments of a standard IF formula.read more of Excel. This is because the former is easier to understand and execute than the latter.

The steps to use the Select Case statement of VBA are listed as follows:

  1. Create a command button and place it in the Excel worksheet. When the command button is clicked, a macroA macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data. For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.
    read more
    runs. The running of the macro performs an action.
  2. Right-click the command button and choose the option “view code.” The Visual Basic Editor opens.
  3. Enter the code between the CommandButton function and End Sub.
  4. Debug and compile the code to identify the syntax errors.
  5. Change the input values to observe the different outputs.

Note 1: The user-defined functions (UDF) are customized functions that cater to the specific needs of the user.

Note 2: Every time the input is changed (in point e), the “expression for testing” changes. As a result, the conditions that match this expression change. Hence, different codes are executed each time the input values change.

VBA Select Case Examples

You can download this VBA Select Case Excel Template here – VBA Select Case Excel Template

Example #1–“Expression for Testing” is Entered Directly

In the following code, the “expression for testing” is A=20 and the Case statements are 10, 20, 30, and 40. There is also a Case Else statement in this code.

Private Sub Selcaseexmample ()
Dim A As Integer
A = 20
 
Select Case A
  
Case 10
 MsgBox "First Case is matched!"

Case 20
 MsgBox "The Second Case is matched!"

Case 30
 MsgBox "Third Case is matched in Select Case!"

Case 40
 MsgBox "Fourth Case is matched in Select Case!"

Case Else
 MsgBox "None of the Cases match!"

End Select
End Sub

On running the preceding code, the following output is obtained.

VBA Select Case

Explanation: The expression A=20 is compared with the four Case statements 10, 20, 30, and 40. A match is found in the second Case statement (Case 20). Consequently, the message of the second Case statement is displayed, which is “the second Case is matched.”

Had the expression not matched with any of the Case statements, the message of the Case Else statement would have been displayed.

Note: The MsgBox function of VBA displays a dialog box containing a customized message.

Example #2–“Expression for Testing” is Compared with a Range of Values Using the “To” Keyword

In the following code, the “expression for testing” is collected from the user with the help of the InputBox function of VBA. There are four Case statements, namely Case 1 To 36, Case 37 To 55, Case 56 To 80, and Case 81 To 100. There is also a Case Else statement in the code.

Private Sub Selcasetoexample ()
Dim studentmarks As Integer
studentmarks = InputBox("Enter marks between 1 to 100.")
  
Select Case studentmarks
    
  Case 1 To 36
   MsgBox "Fail!"
   
  Case 37 To 55
   MsgBox "C Grade"
 
  Case 56 To 80
   MsgBox "B Grade"
  
  Case 81 To 100
   MsgBox "A Grade"
  
  Case Else
   MsgBox "Out of range"

End Select
End Sub

On running the preceding code, the user is asked for input. Assume that the user enters 90. So, the following output is obtained.

VBA Select Case 1

Explanation: The Case statements of the preceding code contain a range of values. Notice that in the code, each number preceding the To keyword is smaller than the number succeeding this keyword.

The “expression for testing” is entered as 90 by the user. This expression matches the fourth Case statement (Case 81 to 100). So, the code in this Case statement is executed. Hence, the message “A grade” is returned by VBA. This output is displayed in a dialog box due to the usage of the MsgBox function in the code.

Both numbers (preceding and succeeding the To keyword) of the range are inclusive. So, had the user entered 81, it would have again matched with the fourth Case statement. However, had a number greater than 100 been entered, the output would have been “out of range.” This message is defined in the Case Else statement of the code.

Note: The InputBox function collects the input from the user through a dialog box. The message shown in this dialog box is the same as that entered in the InputBox function of the code.

Example #3–“Expression for Testing” is Compared with Numbers Using the “Is” Keyword

In the following code, the “expression for testing” is collected from the user. There are two Case statements, namely Case Is < 200 and Case Is >= 200. There is no Case Else statement in the code.

Sub CheckNumber()
  Dim NumInput As Integer
  NumInput = InputBox("Please enter a number.")
  
Select Case NumInput
  
Case Is < 200
 MsgBox "You entered a number less than 200"
    
Case Is >= 200
 MsgBox "You entered a number greater than or equal to 200"

End Select
End Sub

On running the preceding code, a dialog box containing the message “please enter a number” is displayed. Assume that the user enters 200. So, the following output is displayed.

vba select case example 3

Explanation: Observe that the two logical operators (< and >=) in the code are preceded by the “Is” keyword. Had this keyword not been supplied, VBA would have automatically inserted it before the logical operators.

The “expression for testing” is entered by the user as 200. This expression is compared with the two Case statements of the preceding code. A match is found in the second Case statement. This is because 200 is not greater than but is equal to 200.

Notice that there is no Case Else statement in the preceding code. This is because whatever number the user enters, it falls within either of the two Case statements. So, one of the two Case statements will always be true. Hence, the Case Else statement is not required as it runs only when all Case statements evaluate to false.

Example #4–“Expression for Testing” is Entered in a Cell and Evaluated by the Command Button

In the following code, the “expression for testing” is taken from cell A1 of the Excel worksheet. There are three Case statements and one Case Else statement.

Sub color()
Dim color As String
color = Range("A1").Value
  
Select Case color

Case "Red", "Green", "Yellow"
 Range("B1").Value = 1
    
Case "White", "Black", "Brown"
 Range("B1").Value = 2
    
Case "Blue", "Sky Blue"
 Range("B1").Value = 3
    
Case Else
 Range("B1").Value = 4

End Select
End Sub

Further, a command button has been created in the worksheet with the help of ActiveX controls. The input entered in cell A1, the command button, and the output obtained in cell B1 are shown in the following image.

vba select case example 4

Explanation: The preceding code is executed by clicking the command button of the Excel worksheet. Notice that multiple expressions of each Case statement are separated by commas (like “Red”, “Green”, “Yellow”).

The “expression for testing” is entered as “pink” in cell A1. This expression matches none of the three Case statements specified in the code. Consequently, the code of the Case Else statement is executed. So, the output in cell B1 is 4.

Had the user entered a color (in cell A1) specified in any of the three Case statements, the corresponding code would have run. For instance, had the user entered “White” in cell A1 (without the double quotes and with “W” capital), the output in cell B1 would have been 2.

Hence, a change in the input of cell A1 causes the output of cell B1 to change.

Example #5–“Expression for Testing” is Divided by 2 with the MOD Operator of VBA

In the following code, the “expression for testing” is collected from the user. There are two Case statements, namely Case True and Case False. The Case Else statement is not there in the code.

Sub CheckOddEven()
CheckValue = InputBox("Enter a number.")

Select Case (CheckValue Mod 2) = 0
 
Case True
 MsgBox "The number is even"
  
Case False
 MsgBox "The number is odd"

End Select
End Sub

On running the preceding code, a dialog box with the message “enter the number” is displayed. Assume that the user enters 10. The output obtained is shown in the following image.

example 5

Explanation: The “expression for testing” entered by the user is 10. This expression is divided by 2 with the help of the MOD operatorVBA MOD is the same as the application in mathematics. When a number is divided by its divisor, this function gives us the remainder from the division. However, it is not a function in VBA; rather it is an operator.read more. If the remainder is equal to zero, the number is divisible by 2. Such a number is even. If the remainder is not equal to zero, the number is not divisible by 2 and is odd.

Since 10 is divisible by 2, the code of the Case True statement is executed. Hence, the output is the message “the number is even.” Notice that a Case Else statement is not required in the preceding code. This is because either of the two Case statements will be true at all times.

Note: The MOD operator of VBA divides one number by the other and returns the remainder as the output.

Example #6–Nested Select Case Statements Where “Expression for Testing” is the Current Date

In the following code, the “expression for testing” is the current date. There are two Select Case statements [Select Case Weekday (Now) and Case 1,7], one Case Statement (Case 1), and two Case Else statements.

Sub TestWeekday()

Select Case Weekday(Now)

Case 1, 7
 Select Case Weekday(Now)
  
Case 1
 MsgBox "Today is Sunday"
  
Case Else
 MsgBox "Today is Saturday"
  
End Select

Case Else
  MsgBox "Today is a Weekday"

End Select
End Sub

On running the preceding code, the output obtained is shown in the following image.

example 6

Explanation: The inner Select Case statement (Case 1, 7) is the Case statement of the outer Select Case statement [Select Case Weekday (Now)]. The outer Select Case statement checks whether the current date is a weekday, Saturday or Sunday.

When the NOW VBA functionNOW is a date and time function in VBA which is used to get the current system date and time. VBA Now function does not takes any arguments and the return output for this function is date.read more is enclosed within the VBA WEEKDAY functionWeekday in VBA is a date and time function to identify the weekday of a given date provided as an input. This function returns an integer value from 1 to 7 range. There is an optional argument provided to this function which is the first day of the week.read more, the latter returns a day of the week that corresponds with the current date. If the output of the WEEKDAY function is 1, the message to be displayed is “today is Sunday.” If the output of the WEEKDAY function is 7, the message to be displayed is “today is Saturday.” This is because, in the preceding code, VBA considers 1 and 7 as Sunday and Saturday respectively.

The message “today is a weekday” will be returned when the output of the WEEKDAY function is other than 1 and 7. So, the second Case Else statement is executed when Case 1 (today is Sunday) and the first Case Else statements (today is Saturday) are false.

Since this article has been created on a weekday, the output of the Select Case statement is “today is a weekday.”

Note 1: The NOW function of VBA returns the current date and time. This function does not take any arguments. The WEEKDAY function of VBA returns the day of the week corresponding to the specified date.

Note 2: Every nested Select Case statement should necessarily contain a matching End Select statement.

The important points related to the Select Case statement of VBA are listed as follows:

  • The Is keyword used in the Case statement and Case Else statement is different from the Is operator of VBA.
  • The codes of the Select Case statement of VBA can run successfully if macros have been enabled.
  • The “expression for testing” entered in the dialog box should be in accordance with the message of the InputBox function of VBA.

Note: To know more about enabling macrosTo enable macros simply means to run or execute a macro in a particular file in order to save the time spent on repetitive actions. To enable macros, select “enable all macros” from the “trust center” of the File tab (in the “options” button).
read more
, click the given hyperlink.

Frequently Asked Questions

1. Define the Select Case statement of Excel VBA.

The Select Case statement is used to compare an expression with multiple Case statements. If a Case statement matches the expression, the corresponding code is executed. However, if a Case statement does not match the expression, the next Case statement is evaluated.

The evaluation of Case statements continues till a match is found or till the Case Else or End Select statement. Once a match is found in any of the Case statements, no further Case statements are tested. The Case Else statement is optional and its code is executed when none of the Case statements is true.

Note: For details related to the working of the VBA Select Case statement, refer to the examples of this article.

2. How is the Select Case statement of Excel VBA written?

The steps to write the Select Case statement of Excel VBA are listed as follows:

a. Specify a single expression that needs to be compared with multiple Case statements. This expression can be numeric or textual. Note that the expression is evaluated only once and is stated at the beginning of the Select Case structure.
b. Specify the Case statements. Each Case statement should consist of one or more conditions (or possible outcomes) followed by a code. For stating multiple conditions within the same Case statements, use the comma as the separator.
c. Specify the Case Else statement. The code of this statement will be executed if none of the Case statements match the expression. Though it is optional to specify the Case Else statement, it is recommended to be included in the Select Case structure.
d. State the End Select statement. This statement is necessarily required as it terminates the Select Case structure. If no Case statement matches the expression and there is no Case Else statement, control passes to the End Select statement.

Note 1: If the expression (in point a) is to be collected as an input from the user, a customized message must be stated within the InputBox function of VBA.

Note 2: For more details related to the writing of the VBA Select Case statement, refer to the codes of the examples and their explanations given in this article.

3. Differentiate between the Select Case and If Then Else statements of Excel VBA.

The differences between the Select Case and If Then Else statements of Excel VBA are listed as follows:

a. The Select Case statement evaluates a single expression at a time, while the If Then Else statement can evaluate multiple expressions simultaneously.
b. The Select Case statement checks one expression for multiple possible outcomes, while the If Then Else statement checks multiple expressions for multiple possible outcomes.
c. In a Select Case statement, any number of Case statements can be included without impacting the readability of the code. In contrast, a lot of conditions tend to make the If Then Else statement unreadable.
d. It is easy to write, edit, and make changes to the Select Case statement. On the other hand, it is difficult to write, identify errors, and make changes to the If Then Else statement.

In both, Select Case and If Then Else statements, a code is executed depending on whether a condition is met or not. So, based on the requirement and convenience, one can choose either of the two statements.

Recommended Articles

This has been a guide to the Excel VBA Select Case statement. Here we discuss how to use the Excel VBA Select Case statements with certain keywords (like Is, To) along with examples and a downloadable Excel template. Take a look at the following Excel VBA articles–

  • VBA LCase
  • Excel VBA InputBox
  • FIND VBA Function
  • What is VBA Range?

Key Points

  • With SELECT CASE, you can test multiple conditions, especially when you are working on more than two.
  • The code you write with SELECT CASE is way more structured than standard conditional code.
  • It is easier to modify it when you need to adjust one or more of the values in the code.

What is VBA Select Case

VBA SELECT CASE is a statement to test multiple conditions. In this statement, you can specify one condition and then specify a code to execute if that condition is true and then specify a second condition and a code to run if that condition is true. In this way, you can specify multiple conditions and multiple statements.

The syntax for select case

Below is the syntax that you need to follow to write a select case statement.

Select Case Test Expression

	Case (Condition to Test)
	Statement1 [Line of Code to Run if CASE 1 is TRUE]

	Case (Condition to Test)
	Statement1 [Line of Code to Run if CASE 2 is TRUE]

	Case Else
	Statement [Line of Code to Run if no CASE is TRUE]

End Select

In SELECT CASE syntax starts with the keyword “Select” and ends with “End Select”. To understand its syntax, we need to split it into four parts:

  • In the FIRST part, you need to specify the “Test Expression” on which all the conditions get tests.
  • After that, in the SECOND part, you need to specify the case to test (that means condition to test).
  • Now in the THIRD part, you need to write another case where you need to test if the condition in the second part is not TRUE.
  • In the end, in the FOURTH part, you need to specify an outcome that should come when both the above cases are not TRUE.

A simple example to understand a select case statement

The syntax of the SELECT CASE is self-explanatory and quite easy to follow while writing code. But let’s take an example and understand it completely. Below you have a simple code to test the value from cell A1.

Sub SelectCaseExample1()

    Select Case Range("A1").Value

        Case "Yes"
            MsgBox "It's a Yes."

        Case "No"
            MsgBox "It's a No"

        Case Else
            MsgBox "Can't Say"  
      
    End Select

End Sub

Now let’s understand this code with each line:

  • FIRST, you have the SELECT CASE keyword and the cell A1 to use as an expression for testing the condition.
  • SECOND, you have the keyword CASE and the condition (“YES”) to check from cell A1 and code to show a message box with the message “It’s a Yes” if the condition mentioned in the case1 is true.
  • THIRD, you again have the keyword case and the condition (“No”) to check from cell A1 and code to show a message box with the message “It’s a No” if the condition mentioned in case two is true.
  • FOURTH, you have the keyword CASE ELSE and a line of code to show a message box with a message “Can’t Say” if none of the cases are true.
  • FIFTH, you have the END SELECT keyword to end the SELECT CASE statement.

Related: VBA MESSAGE BOX

Important Points

  • It can test multiple conditions and execute a line of code based on the result.
  • You can use comparison operators (=, >, <, <>, >=, <=) while testing for a condition by using the Is keyword.
  • You can use a comma to test more than one condition within a single case.
  • You can also use a range of numbers while testing a condition in a single case.
  • When one condition is met, VBA stops to test the rest of the cases from the statement.
  • You can also add a case else section at the end to execute a line of code when none of the conditions are met.
  • You can skip using the CASE END statement.

More Examples to use Select Case

It’s time to use the SELECT CASE in different ways, and below are some of the useful and essential examples that you can learn.

100 Excel Macro Examples

1. Select Case with Numbers

While writing a VBA code for the SELECT CASE statement, you can use operators to compare values. Now in the below code, you have >,<, and = operators to test the conditions.

Sub SelectCaseExample1()

    Select Case Range("A1").Value

        Case Is >= 45
            MsgBox "Pass"    

        Case Is < 45
            MsgBox "Fail"    
   
    End Select

End Sub    
  • The first case in this statement checks if the value from cell A1 is greater than or equal to 45 or not and returns a message box with the message “Pass”.
  • And the second case in the statement checks if the value from cell A1 is lower than 45 and returns a message box with the message “Fail”. 

2. Select Case with a Range of Numbers

You can also use a range of numbers to test a condition. In the below code, you have a condition with a range of numbers in each case to test.

Sub SelectCaseExample2()

    Select Case Range(“A1”).Value

        Case 45 To 100
            MsgBox “Pass”    
    
        Case 0 To 44
            MsgBox “Fail”       

        Case Else
            MsgBox “Out of Range”           

    End Select   

End Sub
  • The first case in the statement checks the number from cell A1 using the range of numbers from 45 to 100 and returns the “Pass” if the value falls under this range.
  • The second statement has a range of 0 to 44 to test with the value from cell A1 and returns “Fail” if the value falls under this range.
  • The third statement is case else show a message box with the message “Out of Range” if cases one and two are false.

3. Using the Colon Operator

While writing code for the SELECT CASE, you can use colon operators to write the entire case in one line.

In the below code, the line starts with the case and then the condition to test and then a colon, and then the statement to run in that case is true.

Sub SelectCaseExample3()

    Select Case Range(“A1”).Value   

        Case 45 To 100: MsgBox “Pass”           

        Case 0 To 44: MsgBox “Fail”           

        Case Else: MsgBox “Out of Range”           

    End Select   

End Sub

4. Use Select Case with Multiple Conditions

Just like defining a range for a case, you can also specify multiple values to test for the condition. In the below code, each case has three numbers to test.

Sub SelectCaseExample()

    Select Case Range("A1").Value

        Case 1, 3, 5
            MsgBox "Yes"
            
        Case 2, 4, 6
            MsgBox "No"
            
        Case Else
            MsgBox "Out of range"
            
    End Select
        
End Sub
  • The first case of this code will test the value from the cell if it is 1, 3, or 5 and will return “Yes” in a message box.
  • And the second case of this code will test the value from cell A1 if it’s 2, 4, or 6.

5. Using Select Case in a Custom Function

You can also use the SELECT CASE while writing code for a VBA Function.

Function udfGrade(student_marks As Integer)

Dim myGrade As String

Select Case student_marks

    Case Is < 40: myGrade = “Bad”

    Case 41 To 50: myGrade = “Average”

    Case 51 To 60: myGrade = “Good”

    Case 61 To 80: myGrade = “Very Good”   

    Case 81 To 100: myGrade = “Excellent”

End Select

udfGrade = myGrade

End Function

In the above function, it has five cases to check for the score of the students from a cell. All 5 cases use a range of numbers and return the value defined in the statement.

6. Using Select Case from Nested Conditions

You can also create a nested condition statement. What I’m trying to say is you can write a code to test multiple conditions with the select case.

Imagine if you want to write a code that can test conditions based on the values from two different cells.

Sub SelectCaseStatement()

    Select Case Range("A2")
    
        Case "Boy"
        
            Select Case Range("B2")
                Case "Commerce": MsgBox "Boy (Commerce)"
                Case "Science": MsgBox "Boy (Science)"
            End Select
            
        Case "Girl"
        
            Select Case Range("B2")
                Case "Commerce": MsgBox "Girl (Commerce)"
                Case "Science": MsgBox "Girl (Science)"
            End Select
            
    End Select
    
End Sub

In the above code, you have three select case statements. There is one main statement that checks for the value from the cell A2 if it is “Boy” or “Girl”.

And then, based on the result, two more statements run and check for the value from cell B2 if it is Commerce or Science.

SELECT CASE Vs. IF THEN ELSE Statement

  • When you want to test multiple conditions, it’s easy to write a code using the SELECT CASE instead of IF-THEN.
  • Even it is easy to edit and make changes in a SELECT CASE statement compared to IF-THEN.

Excel VBA Select Case: Step-by-Step Examples to Use the Select Case Statement in MacrosIn this Excel VBA Select Case Tutorial, you learn how to use the Select Case statement in macros.

This Excel VBA Select Case Tutorial is currently under development. Subscribe to the Power Spreadsheets Newsletter and get future updates to this Excel VBA Select Case Tutorial.

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples below. Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

The VBA code in the Excel workbook that accompanies this Excel VBA Select Case Tutorial is (always) stored in the Visual Basic Editor (VBE). If you don’t know how to work with the VBE, I suggest you read my Visual Basic Editor (VBE) Tutorial. I link to this Tutorial in the Related Excel Macro and VBA Training Materials and Resources Section below.

The following Excel Macro and VBA Tutorials may help you better understand and implement the contents below.

  • Tutorials about general macro and VBA constructs and structures:
    • Tutorials for Beginners:
      • Excel Macros: Click here to open.
      • Excel VBA: Click here to open.
    • Enable macros in Excel: Click here to open.
    • Work with the Visual Basic Editor (VBE): Click here to open.
    • Create Sub procedures: Click here to open.
    • Work with:
      • Variables: Click here to open.
      • Data types: Click here to open.
      • Functions: Click here to open.
  • Tutorials with practical VBA applications and macro examples:
    • Excel VBA Change Font Color Based on Cell Value: Click here to open.
    • Create a message box: Click here to open.
    • Create an input box: Click here to open.

This Excel VBA Select Case Tutorial is part of a more comprehensive series of Excel VBA Select Case Tutorials.

  • Excel VBA Select Case Tutorial: Click here to open.
  • Excel VBA Select Case Or: Click here to open.
  • Excel VBA Select Case And Operator: Click here to open.
  • Excel VBA Select Case Multiple Test Expressions: Click here to open.
  • Excel VBA Select Case Like Wildcard: Click here to open.
  • Excel VBA Select Case Inside For… Next Loop: Click here to open.
  • Excel VBA Select Case Range of Cells: Click here to open.

You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives. The following are some of my most popular Excel Tutorials and Training Resources:

  • Excel Keyboard Shortcuts Cheat Sheet: Click here to open.
  • Work with the Excel XLOOKUP Function: Click here to open.
  • Excel Power Query (Get & Transform) Tutorial for Beginners: Click here to open.

If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:

  • Premium Courses at the Power Spreadsheets Academy: Click here to open.
  • Books at the Power Spreadsheets Library: Click here to open.
  • VBA Cheat Sheets: Click here to open.

If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:

  • Code generators.
  • An extensive code library.
  • The ability to create your own code library.
  • Advanced coding tools.

If you need help with Excel tasks/projects, you may be interested in working with me: Click here to learn more about working with me.


Get immediate free access to the Excel VBA Select Case example workbook

(1) Excel VBA Select Case Without Case Else

In this Section, you learn how to create a basic Excel VBA Select Case statement (without the Case Else clause) to conditionally execute a set of statements based on an expression’s value.

Excel VBA Select Case Without Case Else Snippet Template/Structure

The following is the Excel VBA Select Case Without Case Else snippet template/structure I explain (step-by-step) in the Sections below.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Step-by-Step Process to Set Up an Excel VBA Select Case Without Case Else Statement

Do the following to create an Excel VBA Select Case Without Case Else statement:

(1) Enter the opening and closing statements of the Select Case statement.

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case '...
    '...
End Select

(2) Specify the test expression VBA uses to identify the set of statements to execute: TestExpression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    '...
End Select

(3) Specify the case expressions used by VBA to identify the set of statements to execute:

  • CaseExpression1.
  • CaseExpression2.
  • CaseExpression#.

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

Each case expression is preceded by the Case keyword:

  • Case CaseExpression1.
  • Case CaseExpression2.
  • Case CaseExpression#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        '...
    Case CaseExpression2
        '...
    '...
    Case CaseExpression#
        '...
End Select

The Case keyword plus associated case expression (Case CaseExpression#) form a Case clause.

When the test expression (you specified in step #2) matches an individual case expression, the Select Case statement:

  1. Executes the set of statements (you specify in step #4) associated to the applicable Case clause (whose case expression matched the test expression); and
  2. Exits the Select Case statement.

(4) Specify the set of statements to be executed when the applicable case expression (you specified in step #3) matches the test expression (you specified in step #2).

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Additional Cues for Excel VBA Select Case Without Case Else

(1) The Select Case statement is an alternative to complex If… Then… Else statements (Select Case vs. If… Then… Else). Consider using the Select Case statement when dealing with (more) complex cases.

(2) Consider indenting the statements inside Select Case statements.

(3) Consider working with the separator character (:) to separate the Case clause (Case CaseExpression#) and the statements to be executed (CaseStatements#), when the following 2 conditions are met:

  1. The case results in a single statement (CaseStatement#) being executed; and
  2. The resulting line of VBA code is not excessively long.

(4) You have a significant degree of flexibility when specifying case expressions inside a Select Case statement.

Please refer to the Section on Excel VBA Select Case Multiple Conditions (in this Excel VBA Select Case Tutorial) for a more detailed explanation on how to create a Select Case statement to conditionally execute a set of statements based on multiple conditions (grouping several cases inside a single case expression).

(5) As a general rule: Organize case expressions:

  • By decreasing order of probability.
  • In such a way that any case expression excludes subsequent case expressions.

(6) The Select Case statement contains a set of catch-all statements executed if no case expression matches the test expression. These statements follow the Case Else keyword. The Case Else keyword (and clause) is optional.


Get immediate free access to the Excel VBA Select Case example workbook

Excel VBA Select Case Without Case Else Example Macro

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples inside this Tutorial (including this Select Case Without Case Else example). Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

I create the Excel VBA Select Case without Case Else example macro as follows:

(1) Declare a Sub procedure (SelectCaseWithoutCaseElse).

Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    '...
    
End Sub

(2) Declare a variable (MyWeekdayMessage) of the String data type.

Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/

    'Declare variable to represent message to be displayed in message box
    Dim MyWeekdayMessage As String

    '...
    
End Sub

(3) Enter the opening and closing statements of the Select Case statement.

Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/

    'Declare variable to represent message to be displayed in message box
    Dim MyWeekdayMessage As String

    Select Case '...
        '...
    End Select
    
    '...
    
End Sub

(4) Specify the test expression VBA uses to identify the set of statements to execute.

The test expression I use (Weekday(Date:=Date, FirstDayOfWeek:=vbMonday)) returns an integer (1 to 7) representing the current day of the week.

Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/

    'Declare variable to represent message to be displayed in message box
    Dim MyWeekdayMessage As String

    Select Case Weekday(Date:=Date, FirstDayOfWeek:=vbMonday)
        '...
    End Select
    
    '...
    
End Sub

(5) Specify the case expressions used by VBA to identify the set of statements to execute.

The test expression I specified in step #4 returns an integer between 1 and 7. The case expressions I specify are (therefore):

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/

    'Declare variable to represent message to be displayed in message box
    Dim MyWeekdayMessage As String

    Select Case Weekday(Date:=Date, FirstDayOfWeek:=vbMonday)
        Case 1: '...
        Case 2: '...
        Case 3: '...
        Case 4: '...
        Case 5: '...
        Case 6: '...
        Case 7: '...
    End Select
    
    '...
    
End Sub

(6) Specify the statement to be executed when the applicable case expression (I specified in step #5) matches the test expression (I specified in step #4).

The statements I use assign a string to the MyWeekdayMessage variable (I declared in step #2). The assigned string varies, depending on the applicable case expression (I specified in step #5):

  • Case expression is 1: Assigned string is “It’s Monday”.
  • Case expression is 2: Assigned string is “It’s Tuesday”.
  • Case expression is 3: Assigned string is “It’s Wednesday”.
  • Case expression is 4: Assigned string is “It’s Thursday”.
  • Case expression is 5: Assigned string is “It’s Friday”.
  • Case expression is 6: Assigned string is “It’s Saturday”.
  • Case expression is 7: Assigned string is “It’s Sunday”.
Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/

    'Declare variable to represent message to be displayed in message box
    Dim MyWeekdayMessage As String

    'Assign a string to the MyWeekdayMessage variable, depending on the current day of the week
    Select Case Weekday(Date:=Date, FirstDayOfWeek:=vbMonday)
        Case 1: MyWeekdayMessage = "It's Monday"
        Case 2: MyWeekdayMessage = "It's Tuesday"
        Case 3: MyWeekdayMessage = "It's Wednesday"
        Case 4: MyWeekdayMessage = "It's Thursday"
        Case 5: MyWeekdayMessage = "It's Friday"
        Case 6: MyWeekdayMessage = "It's Saturday"
        Case 7: MyWeekdayMessage = "It's Sunday"
    End Select
    
    '...
    
End Sub

(6) Display a message box (MsgBox) with the value held by the MyWeekdayMessage variable.

Sub SelectCaseWithoutCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyWeekdayMessage As String
    
    'Assign a string to the MyWeekdayMessage variable, depending on the current day of the week
    Select Case Weekday(Date:=Date, FirstDayOfWeek:=vbMonday)
        Case 1: MyWeekdayMessage = "It's Monday"
        Case 2: MyWeekdayMessage = "It's Tuesday"
        Case 3: MyWeekdayMessage = "It's Wednesday"
        Case 4: MyWeekdayMessage = "It's Thursday"
        Case 5: MyWeekdayMessage = "It's Friday"
        Case 6: MyWeekdayMessage = "It's Saturday"
        Case 7: MyWeekdayMessage = "It's Sunday"
    End Select
    
    'Display message box with string held by the MyWeekdayMessage variable
    MsgBox MyWeekdayMessage
    
End Sub

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case without Case Else example macro. I execute the example macro (and create this screenshot) on a Sunday.

Excel VBA Select Case Without Case Else example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Select Case Without Case Else vs. If… Then… ElseIf… Example Macro

The following If… Then… ElseIf… example macro is an equivalent example macro (to the Select Case without Case Else example macro I explain above) working with the If… Then… Else statement (vs. the Select Case statement).

Sub SelectCaseWithoutCaseElseVsIfThenElseIf()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variables to represent:
        '(1) Number representing day of the week
        '(2) Message to be displayed in message box
    Dim MyWeekday As Integer
    Dim MyWeekdayMessage As String
    
    'Assign number representing day of the week to the MyWeekday variable
    MyWeekday = Weekday(Date:=Date, FirstDayOfWeek:=vbMonday)
    
    'Assign a string to the MyWeekdayMessage variable, depending on the current day of the week
    If MyWeekday = 1 Then
        MyWeekdayMessage = "It's Monday"
    ElseIf MyWeekday = 2 Then
        MyWeekdayMessage = "It's Tuesday"
    ElseIf MyWeekday = 3 Then
        MyWeekdayMessage = "It's Wednesday"
    ElseIf MyWeekday = 4 Then
        MyWeekdayMessage = "It's Thursday"
    ElseIf MyWeekday = 5 Then
        MyWeekdayMessage = "It's Friday"
    ElseIf MyWeekday = 6 Then
        MyWeekdayMessage = "It's Saturday"
    ElseIf MyWeekday = 7 Then
        MyWeekdayMessage = "It's Sunday"
    End If
    
    'Display message box with string held by the MyWeekdayMessage variable
    MsgBox MyWeekdayMessage
    
End Sub

Notice how the Select Case statement results in more efficient VBA code that’s easier to:

  • Read;
  • Follow;
  • Understand; and
  • Work with.

The image below displays the message box shown by Excel when I execute the Excel VBA If… Then… ElseIf… example macro. I execute the example macro (and create this screenshot) on a Sunday.

Excel VBA Select Case Without Case Else vs. If... Then... ElseIf... example macro results


Get immediate free access to the Excel VBA Select Case example workbook

In this Section, you learn how to create a basic Excel VBA Select Case statement (with the Case Else clause) to:

  • Conditionally execute a set of statements based on an expression’s value; and
  • Specify a set of catch-all statements that are executed when none of the conditions you (originally) expected is met.

Excel VBA Select Case Else Snippet Template/Structure

The following is the Excel VBA Select Case Else snippet template/structure I explain (step-by-step) in the Sections below.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Step-by-Step Process to Set Up an Excel VBA Select Case Else Statement

Do the following to create an Excel VBA Select Case Else statement:

(1) Enter the opening and closing statements of the Select Case statement.

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case '...
    '...
End Select

(2) Specify the test expression VBA uses to identify the set of statements to execute: TestExpression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    '...
End Select

(3) Specify the case expressions used by VBA to identify the set of statements to execute:

  • CaseExpression1.
  • CaseExpression2.
  • CaseExpression#.

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

Each case expression is preceded by the Case keyword:

  • Case CaseExpression1.
  • Case CaseExpression2.
  • Case CaseExpression#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        '...
    Case CaseExpression2
        '...
    '...
    Case CaseExpression#
        '...
    '...
End Select

The Case keyword plus associated case expression (Case CaseExpression#) form a Case clause.

When the test expression (you specified in step #2) matches an individual case expression, the Select Case statement:

  1. Executes the set of statements (you specify in step #4) associated to the applicable Case clause (whose case expression matched the test expression); and
  2. Exits the Select Case statement.

(4) Specify the set of statements to be executed when the applicable case expression (you specified in step #3) matches the test expression (you specified in step #2).

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
    '...
End Select

(5) Specify the set of statements to be executed if no case expression (you specified in step #3) matches the test expression (you specified in step #2). These catch-all statements follow the Case Else keyword.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Additional Cues for Excel VBA Select Case Else

(1) The Select Case statement is an alternative to complex If… Then… Else statements (Select Case vs. If… Then… Else). Consider using the Select Case statement when dealing with (more) complex cases.

(2) Consider indenting the statements inside Select Case statements.

(3) Consider working with the separator character (:) to separate:

  • The Case clause (Case CaseExpression#) and the statements to be executed (CaseStatements#); or
  • The Case Else keyword (Case Else) and the catch-all statements (ElseStatements);

When the following 2 conditions are met:

  1. The case results in a single statement (CaseStatement#) being executed or there’s (only) a single catch-all statement (ElseStatement); and
  2. The resulting line of VBA code is not excessively long.

(3) You have a significant degree of flexibility when specifying case expressions inside a Select Case statement.

Please refer to the Section on Excel VBA Select Case Multiple Conditions (in this Excel VBA Select Case Tutorial) for a more detailed explanation on how to create a Select Case statement to conditionally execute a set of statements based on multiple conditions (grouping several cases inside a single case expression).

(4) As a general rule: Organize case expressions:

  • By decreasing order of probability.
  • In such a way that any case expression excludes subsequent case expressions.

(5) The Case Else keyword/clause (Case Else: ElseStatements) is optional.

Work with the Case Else clause to specify a set of catch-all statements that are executed when none of the conditions you (originally) expected is met (no case expression matches the test expression).

(6) If:

  • You omit the Case Else clause; and
  • No case expression matches the test expression;

Procedure execution continues with the first statement after the end of the Select Case statement (after “End Select”).


Get immediate free access to the Excel VBA Select Case example workbook

Excel VBA Select Case Else Example Macro

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples inside this Tutorial (including this Select Case Else example). Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

I create the Excel VBA Select Case Else example macro as follows:

(1) Declare a Sub procedure (SelectCaseElse).

Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    '…
    
End Sub

(2) Declare a variable (MyMonthPartMessage) of the String data type.

Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    '…
    
End Sub

(3) Enter the opening and closing statements of the Select Case statement.

Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    Select Case '…
        '…
    End Select
    
    '…
    
End Sub

(4) Specify the test expression VBA uses to identify the set of statements to execute.

The test expression I use (Day(Date:=Date)) returns an integer (1 to 31) representing the current day of the month.

Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    Select Case Day(Date:=Date)
        '…
    End Select
    
    '…
    
End Sub

(5) Specify the case expressions used by VBA to identify the set of statements to execute.

The test expression I specified in step #4 returns an integer between 1 and 31. The case expressions I specify are (therefore):

  • 1 To 5.
  • 6 To 10.
  • 11 To 15.
  • 16 To 20.
  • 21 To 25.
Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    Select Case Day(Date:=Date)
        Case 1 To 5: '…
        Case 6 To 10: '…
        Case 11 To 15: '…
        Case 16 To 20: '…
        Case 21 To 25: '…
        '…
    End Select
    
    '…
    
End Sub

(6) Specify the statement to be executed when the applicable case expression (I specified in step #5) matches the test expression (I specified in step #4).

The statements I use assign a string to the MyMonthPartMessage variable (I declared in step #2). The assigned string varies, depending on the applicable case expression (I specified in step #5):

  • Case expression is 1 to 5 (both inclusive): Assigned string is “We’re between the first and the fifth of the month”.
  • Case expression is 6 to 10 (both inclusive): Assigned string is “We’re between the sixth and the tenth of the month”.
  • Case expression is 11 to 15 (both inclusive): Assigned string is “We’re between the eleventh and the fifteenth of the month”.
  • Case expression is 16 to 20 (both inclusive): Assigned string is “We’re between the sixteenth and the twentieth of the month”.
  • Case expression is 21 to 25 (both inclusive): Assigned string is “We’re between the twenty-first and the twenty-fifth of the month”.
Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    'Assign a string to the MyMonthPartMessage variable, depending on the current day of the month
    Select Case Day(Date:=Date)
        Case 1 To 5: MyMonthPartMessage = "We're between the first and the fifth of the month"
        Case 6 To 10: MyMonthPartMessage = "We're between the sixth and the tenth of the month"
        Case 11 To 15: MyMonthPartMessage = "We're between the eleventh and the fifteenth of the month"
        Case 16 To 20: MyMonthPartMessage = "We're between the sixteenth and the twentieth of the month"
        Case 21 To 25: MyMonthPartMessage = "We're between the twenty-first and the twenty-fifth of the month"
        '…
    End Select
    
    '…
    
End Sub

(7) Specify the catch-all statement to be executed if no case expression (from the case expressions I specified in step #5) matches the test expression (I specified in step #4).

The statement I use assigns a string to the MyMonthPartMessage variable (I declared in step #2): “We’re past the twenty-fifth of the month”.

Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    'Assign a string to the MyMonthPartMessage variable, depending on the current day of the month
    Select Case Day(Date:=Date)
        Case 1 To 5: MyMonthPartMessage = "We're between the first and the fifth of the month"
        Case 6 To 10: MyMonthPartMessage = "We're between the sixth and the tenth of the month"
        Case 11 To 15: MyMonthPartMessage = "We're between the eleventh and the fifteenth of the month"
        Case 16 To 20: MyMonthPartMessage = "We're between the sixteenth and the twentieth of the month"
        Case 21 To 25: MyMonthPartMessage = "We're between the twenty-first and the twenty-fifth of the month"
        Case Else: MyMonthPartMessage = "We're past the twenty-fifth of the month"
    End Select
    
    '…
    
End Sub

(8) Display a message box (MsgBox) with the value held by the MyMonthPartMessage variable.

Sub SelectCaseElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthPartMessage As String
    
    'Assign a string to the MyMonthPartMessage variable, depending on the current day of the month
    Select Case Day(Date:=Date)
        Case 1 To 5: MyMonthPartMessage = "We're between the first and the fifth of the month"
        Case 6 To 10: MyMonthPartMessage = "We're between the sixth and the tenth of the month"
        Case 11 To 15: MyMonthPartMessage = "We're between the eleventh and the fifteenth of the month"
        Case 16 To 20: MyMonthPartMessage = "We're between the sixteenth and the twentieth of the month"
        Case 21 To 25: MyMonthPartMessage = "We're between the twenty-first and the twenty-fifth of the month"
        Case Else: MyMonthPartMessage = "We're past the twenty-fifth of the month"
    End Select
    
    'Display message box with string held by the MyMonthPartMessage variable
    MsgBox MyMonthPartMessage
    
End Sub

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case Else example macro. I execute the example macro (and create this screenshot) on day 13 of the month.

Excel VBA Select Case Else example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Select Case Else vs. If… Then… ElseIf… Else Example Macro

The following If… Then… ElseIf… Else example macro is an equivalent example macro (to the Select Case Else example macro I explain above) working with the If… Then… Else statement (vs. the Select Case statement).

Sub SelectCaseElseVsIfThenElseIfElse()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variables to represent:
        '(1) Number representing day of the month
        '(2) Message to be displayed in message box
    Dim MyMonthDay As Integer
    Dim MyMonthPartMessage As String
    
    'Assign number representing day of the month to the MyMonthDay variable
    MyMonthDay = Day(Date:=Date)
    
    'Assign a string to the MyMonthPartMessage variable, depending on the current day of the month
    If MyMonthDay <= 5 Then
        MyMonthPartMessage = "We're between the first and the fifth of the month"
    ElseIf (MyMonthDay >= 6) And (MyMonthDay <= 10) Then
        MyMonthPartMessage = "We're between the sixth and the tenth of the month"
    ElseIf (MyMonthDay >= 11) And (MyMonthDay <= 15) Then
        MyMonthPartMessage = "We're between the eleventh and the fifteenth of the month"
    ElseIf (MyMonthDay >= 16) And (MyMonthDay <= 20) Then
        MyMonthPartMessage = "We're between the sixteenth and the twentieth of the month"
    ElseIf (MyMonthDay >= 21) And (MyMonthDay <= 25) Then
        MyMonthPartMessage = "We're between the twenty-first and the twenty-fifth of the month"
    Else
        MyMonthPartMessage = "We're past the twenty-fifth of the month"
    End If
    
    'Display message box with string held by the MyMonthPartMessage variable
    MsgBox MyMonthPartMessage
    
End Sub

Notice how the Select Case statement results in more efficient VBA code that’s easier to:

  • Read;
  • Follow;
  • Understand; and
  • Work with.

The image below displays the message box shown by Excel when I execute the Excel VBA If… Then… ElseIf… Else example macro. I execute the example macro (and create this screenshot) on day 13 of the month.

Excel VBA Select Case vs. If... Then... ElseIf... Else example macro results


Get immediate free access to the Excel VBA Select Case example workbook

(3) Excel VBA Select Case String

In this Section, you learn how to create an Excel VBA Select Case string statement, to conditionally execute a set of statements based on a string.

Excel VBA Select Case String Formula/Snippet Template/Structure

The following is the Excel VBA Select Case string snippet template/structure I explain (step-by-step) in the Sections below.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case StringTestExpression
    Case StringCaseExpression1
        CaseStatements1
    Case StringCaseExpression2
        CaseStatements2
    '...
    Case StringCaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Step-by-Step Process to Set Up an Excel VBA Select Case String Statement

Do the following to create an Excel VBA Select Case string statement:

(1) Enter the opening and closing statements of the Select Case statement.

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case '...
    '...
End Select

(2) Specify the string test expression VBA uses to identify the set of statements to execute: StringTestExpression.

To create an Excel VBA Select Case string statement, specify this string test expression as:

  • A string; or
  • A string expression.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case StringTestExpression
    '...
End Select

(3) Specify the string case expressions used by VBA to identify the set of statements to execute:

  • StringCaseExpression1.
  • StringCaseExpression2.
  • StringCaseExpression#.

You can (as a general rule) include as many string case expressions as required inside a single Select Case statement.

Each string case expression is preceded by the Case keyword:

  • Case StringCaseExpression1.
  • Case StringCaseExpression2.
  • Case StringCaseExpression#.

To create an Excel VBA Select Case string statement, specify case expressions as:

  • A string; or
  • A string expression.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case StringTestExpression
    Case StringCaseExpression1
        '...
    Case StringCaseExpression2
        '...
    '...
    Case StringCaseExpression#
        '...
    '...
End Select

The Case keyword plus associated string case expression (Case StringCaseExpression#) form a Case clause.

When the string test expression (you specified in step #2) matches an individual string case expression, the Select Case statement:

  1. Executes the set of statements (you specify in step #4) associated to the applicable Case clause (whose string case expression matched the string test expression); and
  2. Exits the Select Case statement.

(4) Specify the set of statements to be executed when the applicable string case expression (you specified in step #3) matches the string test expression (you specified in step #2).

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case StringTestExpression
    Case StringCaseExpression1
        CaseStatements1
    Case StringCaseExpression2
        CaseStatements2
    '...
    Case StringCaseExpression#
        CaseStatements#
    '...
End Select

(5) Specify the set of statements to be executed if no string case expression (you specified in step #3) matches the string test expression (you specified in step #2). These catch-all statements:

  • Follow the Case Else keyword; and
  • Are optional.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case StringTestExpression
    Case StringCaseExpression1
        CaseStatements1
    Case StringCaseExpression2
        CaseStatements2
    '...
    Case StringCaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Additional Cues for Excel VBA Select Case String

(1) The Select Case statement is an alternative to complex If… Then… Else statements (Select Case vs. If… Then… Else). Consider using the Select Case statement when dealing with (more) complex cases.

(2) Consider indenting the statements inside Select Case statements.

(3) Consider working with the separator character (:) to separate:

  • The Case clause (Case StringCaseExpression#) and the statements to be executed (CaseStatements#); or
  • The Case Else keyword (Case Else) and the catch-all statements (ElseStatements);

When the following 2 conditions are met:

  1. The case results in a single statement (CaseStatement#) being executed or there’s (only) a single catch-all statement (ElseStatement); and
  2. The resulting line of VBA code is not excessively long.

(3) You have a significant degree of flexibility when specifying case expressions inside a Select Case statement. This flexibility includes the possibility to group several cases inside a single case expression.

Please refer to the Section on Excel VBA Select Case Multiple Conditions (in this Excel VBA Select Case Tutorial) for a more detailed explanation on how to create a Select Case statement to conditionally execute a set of statements based on multiple conditions (grouping several cases inside a single case expression).

(5) Use the Option Compare statement (at the module level) to specify the default comparison method VBA uses when comparing strings:

  • Option Compare Binary; or
  • Option Compare Text.

Option Compare Binary results in a case sensitive comparison. Option Compare Text results in a case insensitive comparison.

The default string comparison method is binary.

(6) As a general rule: Organize case expressions:

  • By decreasing order of probability.
  • In such a way that any case expression excludes subsequent case expressions.

(7) The Case Else keyword/clause (Case Else: ElseStatements) is optional.

Work with the Case Else clause to specify a set of catch-all statements that are executed when none of the conditions you (originally) expected is met (no string case expression matches the string test expression).

(8) If:

  • You omit the Case Else clause; and
  • No string case expression matches the string test expression;

Procedure execution continues with the first statement after the end of the Select Case statement (after “End Select”).


Get immediate free access to the Excel VBA Select Case example workbook

Excel VBA Select Case String Example Macro

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples inside this Tutorial (including this example). Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

I create the Excel VBA Select Case string example macro as follows:

(1) Declare a Sub procedure (SelectCaseString).

Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    '...
    
End Sub

(2) Declare a variable (MyQuarterMessage) of the String data type.

Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    '...
    
End Sub

(3) Enter the opening and closing statements of the Select Case statement.

Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    Select Case '...
        '...
    End Select
    
    '...
    
End Sub

(4) Specify the string test expression VBA uses to identify the set of statements to execute.

The test expression I use (MonthName(Month(Date:=Date))) returns the current month’s name.

Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    Select Case MonthName(Month(Date:=Date))
        '...
    End Select
    
    '...
    
End Sub

(5) Specify the string case expressions used by VBA to identify the set of statements to execute.

The string test expression I specified in step #4 returns a month’s name (“January” to “December”). Additionally, I use commas to separate multiple strings inside a single string case expression.

The string case expressions I specify are (therefore):

  • “January”, “February”, “March”.
  • “April”, “May”, “June”.
  • “July”, “August”, “September”.
  • “October”, “November”, “December”.
Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String

    Select Case MonthName(Month(Date:=Date))
        Case "January", "February", "March" '...
        Case "April", "May", "June" '...
        Case "July", "August", "September" '...
        Case "October", "November", "December" '...
    End Select
    
    '...
    
End Sub

(6) Specify the statement to be executed when the applicable string case expression (I specified in step #5) matches the string test expression (I specified in step #4).

The statements I use assign a string to the MyQuarterMessage variable (I declared in step #2). The assigned string varies, depending on the applicable string case expression (I specified in step #5):

  • String case expression is “January”, “February”, “March”: Assigned string is “It’s Q1”.
  • String case expression is “April”, “May”, “June”: Assigned string is “It’s Q2”.
  • String case expression is “July”, “August”, “September”: Assigned string is “It’s Q3”.
  • String case expression is “October”, “November”, “December”: Assigned string is “It’s Q4”.
Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    'Assign a string to the MyQuarterMessage variable, depending on the current month
    Select Case MonthName(Month(Date:=Date))
        Case "January", "February", "March": MyQuarterMessage = "It's Q1"
        Case "April", "May", "June": MyQuarterMessage = "It's Q2"
        Case "July", "August", "September": MyQuarterMessage = "It's Q3"
        Case "October", "November", "December": MyQuarterMessage = "It's Q4"
    End Select
    
    '...
    
End Sub

(7) Display a message box (MsgBox) with the value held by the MyQuarterMessage variable.

Sub SelectCaseString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    'Assign a string to the MyQuarterMessage variable, depending on the current month
    Select Case MonthName(Month(Date:=Date))
        Case "January", "February", "March": MyQuarterMessage = "It's Q1"
        Case "April", "May", "June": MyQuarterMessage = "It's Q2"
        Case "July", "August", "September": MyQuarterMessage = "It's Q3"
        Case "October", "November", "December": MyQuarterMessage = "It's Q4"
    End Select
    
    'Display message box with string held by the MyQuarterMessage variable
    MsgBox MyQuarterMessage
    
End Sub

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case string example macro. I execute the example macro (and create this screenshot) during April.

Excel VBA Select Case string example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Select Case String vs. If… Then… Else String Example Macro

The following If… Then… Else string example macro is an equivalent example macro (to the Select Case string example macro I explain above) working with the If… Then… Else statement (vs. the Select Case statement).

Sub SelectCaseStringVsIfThenElseIfString()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variables to represent:
        '(1) Month name
        '(2) Message to be displayed in message box
    Dim MyMonth As String
    Dim MyQuarterMessage As String
    
    'Assign current month's name to the MyMonth variable
    MyMonth = MonthName(Month(Date:=Date))
    
    'Assign a string to the MyQuarterMessage variable, depending on the current month
    If (MyMonth = "January") Or (MyMonth = "February") Or (MyMonth = "March") Then
        MyQuarterMessage = "It's Q1"
    ElseIf (MyMonth = "April") Or (MyMonth = "May") Or (MyMonth = "June") Then
        MyQuarterMessage = "It's Q2"
    ElseIf (MyMonth = "July") Or (MyMonth = "August") Or (MyMonth = "September") Then
        MyQuarterMessage = "It's Q3"
    ElseIf (MyMonth = "October") Or (MyMonth = "November") Or (MyMonth = "December") Then
        MyQuarterMessage = "It's Q4"
    End If
    
    'Display message box with string held by the MyQuarterMessage variable
    MsgBox MyQuarterMessage
    
End Sub

Notice how the Select Case statement results in more efficient VBA code that’s easier to:

  • Read;
  • Follow;
  • Understand; and
  • Work with.

The image below displays the message box shown by Excel when I execute the Excel VBA If… Then… Else string example macro. I execute the example macro (and create this screenshot) during April.

Excel VBA Select Case string vs. If... Then... Else string example macro results


Get immediate free access to the Excel VBA Select Case example workbook

(4) Excel VBA Select Case Between 2 Values

In this Section, you learn how to create an Excel VBA Select Case between 2 values statement to conditionally execute a set of statements based on whether an expression returns a value between 2 (other) values.

Excel VBA Select Case Between 2 Values Snippet Template/Structure

The following is the Excel VBA Select Case between 2 values snippet template/structure I explain (step-by-step) in the Sections below.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case LowerBoundCase1 To UpperBoundCase1
        CaseStatements1
    Case LowerBoundCase2 To UpperBoundCase2
        CaseStatements2
    '...
    Case LowerBoundCase# To UpperBoundCase#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Step-by-Step Process to Set Up an Excel VBA Select Case Between 2 Values Statement

Do the following to create an Excel VBA Select Case between 2 values statement:

(1) Enter the opening and closing statements of the Select Case statement.

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case '...
    '...
End Select

(2) Specify the test expression VBA uses to identify the set of statements to execute, as a numeric expression (an expression that can be evaluated as a number): NumericTestExpression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    '...
End Select

(3) Specify the numeric case expressions used by VBA to identify the set of statements to execute. Use the To keyword to specify a range of values for each single case expression.

  • LowerBoundCase1 To UpperBoundCase1.
  • LowerBoundCase2 To UpperBoundCase2.
  • LowerBoundCase# To UpperBoundCase#.

For these purposes:

  • LowerBoundCase# is the smaller value in the specified range of values; and
  • UpperBoundCase# is the larger value in the specified range of values.

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

Each case expression is preceded by the Case keyword:

  • Case LowerBoundCase1 To UpperBoundCase1.
  • Case LowerBoundCase2 To UpperBoundCase2.
  • Case LowerBoundCase# To UpperBoundCase#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case LowerBoundCase1 To UpperBoundCase1
        '...
    Case LowerBoundCase2 To UpperBoundCase2
        '...
    '...
    Case LowerBoundCase# To UpperBoundCase#
        '...
    '...
End Select

The Case keyword plus associated case expression (Case LowerBoundCase# To UpperBoundCase#) form a Case clause.

When the value returned by the numeric test expression (you specified in step #2) is between a case expression’s 2 values, the Select Case statement:

  1. Executes the set of statements (you specify in step #4) associated to the applicable Case clause (whose case expression matched the test expression); and
  2. Exits the Select Case statement.

(4) Specify the set of statements to be executed when the value returned by the numeric test expression (you specified in step #2) is between a case expression’s 2 values (you specified in step #3).

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case LowerBoundCase1 To UpperBoundCase1
        CaseStatements1
    Case LowerBoundCase2 To UpperBoundCase2
        CaseStatements2
    '...
    Case LowerBoundCase# To UpperBoundCase#
        CaseStatements#
    '...
End Select

(5) Specify the set of statements to be executed if the value returned by the numeric test expression (you specified in step #2) isn’t between any case expression’s 2 values (you specified in step #3). These catch-all statements follow the Case Else keyword.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case LowerBoundCase1 To UpperBoundCase1
        CaseStatements1
    Case LowerBoundCase2 To UpperBoundCase2
        CaseStatements2
    '...
    Case LowerBoundCase# To UpperBoundCase#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Additional Cues for Excel VBA Select Case Between 2 Values

(1) The Select Case statement is an alternative to complex If… Then… Else statements (Select Case vs. If… Then… Else). Consider using the Select Case statement when dealing with (more) complex cases.

(2) Consider indenting the statements inside Select Case statements.

(3) Consider working with the separator character (:) to separate:

  • The Case clause (Case LowerBoundCase# To UpperBoundCase#) and the statements to be executed (CaseStatements#); or
  • The Case Else keyword (Case Else) and the catch-all statements (ElseStatements);

When the following 2 conditions are met:

  1. The case results in a single statement (CaseStatement#) being executed or there’s (only) a single catch-all statement (ElseStatement); and
  2. The resulting line of VBA code is not excessively long.

(3) You have a significant degree of flexibility when specifying case expressions inside a Select Case statement. This flexibility includes the possibility to specify a range of values for a single case expression (as you learned in this Section).

Please refer to the Section on Excel VBA Select Case Multiple Conditions (in this Excel VBA Select Case Tutorial) for a more detailed explanation on how to create a Select Case statement to conditionally execute a set of statements based on multiple conditions (grouping several cases inside a single case expression).

(4) As a general rule: Organize case expressions:

  • By decreasing order of probability.
  • In such a way that any case expression excludes subsequent case expressions.

(5) The Case Else keyword/clause (Case Else: ElseStatements) is optional.

Work with the Case Else clause to specify a set of catch-all statements that are executed when none of the conditions you (originally) expected is met (no case expression matches the test expression).

(6) If:

  • You omit the Case Else clause; and
  • No case expression matches the test expression;

Procedure execution continues with the first statement after the end of the Select Case statement (after “End Select”).


Get immediate free access to the Excel VBA Select Case example workbook

Excel VBA Select Case Between 2 Values Example Macro

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples inside this Tutorial (including this example). Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

I create the Excel VBA Select Case between 2 values example macro as follows:

(1) Declare a Sub procedure (SelectCaseBetween2Values).

Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    '...

End Sub

(2) Declare a variable (MyQuarterMessage) of the String data type.

Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    '...

End Sub

(3) Enter the opening and closing statements of the Select Case statement.

Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    Select Case '...
        '...
    End Select
    
    '...

End Sub

(4) Specify the numeric test expression VBA uses to identify the set of statements to execute, as a numeric expression.

The test expression I use (Month(Date:=Date)) returns an integer (1 to 12) representing the current month of the year.

Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    Select Case Month(Date:=Date)
        '...
    End Select
    
    '...

End Sub

(5) Specify the numeric case expressions used by VBA to identify the set of statements to execute. I use the To keyword to specify a range of values for each single case expression.

The test expression I specified in step #4 returns an integer between 1 and 12.

The case expressions I specify (considering the above) are:

  • 1 To 3.
  • 4 To 6.
  • 7 To 9.
  • 10 To 12.
Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    Select Case Month(Date:=Date)
        Case 1 To 3: '...
        Case 4 To 6: '...
        Case 7 To 9: '...
        Case 10 To 12: '...
    End Select
    
    '...

End Sub

(6) Specify the statement to be executed when the value returned by the numeric test expression (I specified in step #4) is between a case expression’s 2 values (I specified in step #5).

The statements I use assign a string to the MyQuarterMessage variable (I declared in step #2). The assigned string varies, depending on the applicable numeric case expression (I specified in step #5):

  • 1 To 3: Assigned string is “It’s Q1”.
  • 4 To 6: Assigned string is “It’s Q2”.
  • 7 To 9: Assigned string is “It’s Q3”.
  • 10 To 12: Assigned string is “It’s Q4”.
Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    'Assign a string to the MyQuarterMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        Case 1 To 3: MyQuarterMessage = "It's Q1"
        Case 4 To 6: MyQuarterMessage = "It's Q2"
        Case 7 To 9: MyQuarterMessage = "It's Q3"
        Case 10 To 12: MyQuarterMessage = "It's Q4"
    End Select
    
    '...

End Sub

(7) Display a message box (MsgBox) with the value held by the MyQuarterMessage variable.

Sub SelectCaseBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyQuarterMessage As String
    
    'Assign a string to the MyQuarterMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        Case 1 To 3: MyQuarterMessage = "It's Q1"
        Case 4 To 6: MyQuarterMessage = "It's Q2"
        Case 7 To 9: MyQuarterMessage = "It's Q3"
        Case 10 To 12: MyQuarterMessage = "It's Q4"
    End Select
    
    'Display message box with string held by the MyQuarterMessage variable
    MsgBox MyQuarterMessage

End Sub

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case between 2 values example macro. I execute the example macro (and create this screenshot) during April.

Excel VBA Select Case between 2 values example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Select Case Between 2 Values vs. If… Then… ElseIf… Between 2 Values Example Macro

The following If… Then… ElseIf… between 2 values example macro is an equivalent example macro (to the Select Case between 2 values example macro I explain above) working with the If… Then… Else statement (vs. the Select Case statement).

Sub SelectCaseBetween2ValuesVsIfThenElseIfBetween2Values()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variables to represent:
        '(1) Number representing month
        '(2) Message to be displayed in message box
    Dim MyCurrentMonth As Integer
    Dim MyQuarterMessage As String
    
    'Assign number representing month to the MyCurrentMonth variable
    MyCurrentMonth = Month(Date:=Date)
    
    'Assign a string to the MyQuarterMessage variable, depending on the current month
    If (MyCurrentMonth >= 1) And (MyCurrentMonth <= 3) Then
        MyQuarterMessage = "It's Q1"
    ElseIf (MyCurrentMonth >= 4) And (MyCurrentMonth <= 6) Then
        MyQuarterMessage = "It's Q2"
    ElseIf (MyCurrentMonth >= 7) And (MyCurrentMonth <= 9) Then
        MyQuarterMessage = "It's Q3"
    ElseIf (MyCurrentMonth >= 10) And (MyCurrentMonth <= 12) Then
        MyQuarterMessage = "It's Q4"
    End If
    
    'Display message box with string held by the MyQuarterMessage variable
    MsgBox MyQuarterMessage

End Sub

Notice how the Select Case statement results in more efficient VBA code that’s easier to:

  • Read;
  • Follow;
  • Understand; and
  • Work with.

The image below displays the message box shown by Excel when I execute the Excel VBA If… Then… ElseIf… between 2 values example macro. I execute the example macro (and create this screenshot) during April.

Excel VBA Select Case between 2 values vs. If... Then... ElseIf... between 2 values example macro results


Get immediate free access to the Excel VBA Select Case example workbook

(5) Excel VBA Select Case Multiple Values

In this Section, you learn how to create a VBA Select Case multiple values statement to conditionally execute a set of statements based on whether an expression returns one of multiple (other) values.

Excel VBA Select Case Multiple Values Snippet Template/Structure

The following is the Excel VBA Select Case multiple values snippet template/structure I explain (step-by-step) in the Sections below.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case Value1Case1, Value2Case1, ..., Value#Case1
        CaseStatements1
    Case Value1Case2, Value2Case2, ..., Value#Case2
        CaseStatements2
    '...
    Case Value1Case#, Value2Case#, ..., Value#Case#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Step-by-Step Process to Set Up an Excel VBA Select Case Multiple Values Statement

Do the following to create an Excel VBA Select Case multiple values statement:

(1) Enter the opening and closing statements of the Select Case statement.

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case '...
    '...
End Select

(2) Specify the test expression VBA uses to identify the set of statements to execute, as a numeric expression (an expression that can be evaluated as a number): NumericTestExpression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    '...
End Select

(3) Specify the numeric case expressions used by VBA to identify the set of statements to execute. Use commas to separate multiple values inside a single numeric case expression.

  • Value1Case1, Value2Case1, …, Value#Case1.
  • Value1Case2, Value2Case2, …, Value#Case2.
  • Value1Case#, Value2Case#, …, Value#Case#.

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

Each case expression is preceded by the Case keyword:

  • Case Value1Case1, Value2Case1, …, Value#Case1.
  • Case Value1Case2, Value2Case2, …, Value#Case2.
  • Case Value1Case#, Value2Case#, …, Value#Case#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case Value1Case1, Value2Case1, ..., Value#Case1
        '...
    Case Value1Case2, Value2Case2, ..., Value#Case2
        '...
    '...
    Case Value1Case#, Value2Case#, ..., Value#Case#
        '...
    '...
End Select

The Case keyword plus associated case expression (Case Value1Case#, Value2Case#, …, Value#Case#) form a Case clause.

When the value returned by the numeric test expression (you specified in step #2) is equal to one of the multiple values inside a case expression, the Select Case statement:

  1. Executes the set of statements (you specify in step #4) associated to the applicable Case clause (whose case expression matched the test expression); and
  2. Exits the Select Case statement.

(4) Specify the set of statements to be executed when the value returned by the numeric test expression (you specified in step #2) is equal to one of the multiple values (you specified in step #3) inside a case expression.

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case Value1Case1, Value2Case1, ..., Value#Case1
        CaseStatements1
    Case Value1Case2, Value2Case2, ..., Value#Case2
        CaseStatements2
    '...
    Case Value1Case#, Value2Case#, ..., Value#Case#
        CaseStatements#
    '...
End Select

(5) Specify the set of statements to be executed if the value returned by the numeric test expression (you specified in step #2) isn’t equal to any of the multiple values inside any of the case expressions (you specified in step #3). These catch-all statements follow the Case Else keyword.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case NumericTestExpression
    Case Value1Case1, Value2Case1, ..., Value#Case1
        CaseStatements1
    Case Value1Case2, Value2Case2, ..., Value#Case2
        CaseStatements2
    '...
    Case Value1Case#, Value2Case#, ..., Value#Case#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Additional Cues for Excel VBA Select Case Multiple Values

(1) The Select Case statement is an alternative to complex If… Then… Else statements (Select Case vs. If… Then… Else). Consider using the Select Case statement when dealing with (more) complex cases.

(2) Consider indenting the statements inside Select Case statements.

(3) Consider working with the separator character (:) to separate:

  • The Case clause (Case Value1Case#, Value2Case#, …, Value#Case#) and the statements to be executed (CaseStatements#); or
  • The Case Else keyword (Case Else) and the catch-all statements (ElseStatements);

When the following 2 conditions are met:

  1. The case results in a single statement (CaseStatement#) being executed or there’s (only) a single catch-all statement (ElseStatement); and
  2. The resulting line of VBA code is not excessively long.

(3) You have a significant degree of flexibility when specifying case expressions inside a Select Case statement. This flexibility includes the possibility to specify multiple values for a single case expression (as you learned in this Section).

Please refer to the Section on Excel VBA Select Case Multiple Conditions (in this Excel VBA Select Case Tutorial) for a more detailed explanation on how to create a Select Case statement to conditionally execute a set of statements based on multiple conditions (grouping several cases inside a single case expression).

(4) As a general rule: Organize case expressions:

  • By decreasing order of probability.
  • In such a way that any case expression excludes subsequent case expressions.

(5) The Case Else keyword/clause (Case Else: ElseStatements) is optional.

Work with the Case Else clause to specify a set of catch-all statements that are executed when none of the conditions you (originally) expected is met (no case expression matches the test expression).

(6) If:

  • You omit the Case Else clause; and
  • No case expression matches the test expression;

Procedure execution continues with the first statement after the end of the Select Case statement (after “End Select”).


Get immediate free access to the Excel VBA Select Case example workbook

Excel VBA Select Case Multiple Values Example Macro

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples inside this Tutorial (including this example). Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

I create the VBA Select Case multiple values example macro as follows:

(1) Declare a Sub procedure (SelectCaseMultipleValues).

Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    '...

End Sub

(2) Declare a variable (MyMonthMessage) of the String data type.

Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    '...

End Sub

(3) Enter the opening and closing statements of the Select Case statement.

Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    Select Case '...
        '...
    End Select
    
    '...

End Sub

(4) Specify the numeric test expression VBA uses to identify the set of statements to execute, as a numeric expression.

The test expression I use (Month(Date:=Date)) returns an integer (1 to 12) representing the current month of the year.

Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    Select Case Month(Date:=Date)
        '...
    End Select
    
    '...

End Sub

(5) Specify the numeric case expressions used by VBA to identify the set of statements to execute. I use commas to separate multiple values inside a single numeric case expression.

The test expression I specified in step #4 returns an integer between 1 and 12.

The case expressions I specify (considering the above) are:

  • 1, 4, 7, 10.
  • 2, 5, 8, 11.
  • 3, 6, 9, 12.
Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    Select Case Month(Date:=Date)
        Case 1, 4, 7, 10: '...
        Case 2, 5, 8, 11: '...
        Case 3, 6, 9, 12: '...
    End Select
    
    '...

End Sub

(6) Specify the statement to be executed when the value returned by the numeric test expression (I specified in step #4) is equal to one of the multiple values (I specified in step #5) inside a case expression.

The statements I use assign a string to the MyMonthMessage variable (I declared in step #2). The assigned string varies, depending on the applicable numeric case expression (I specified in step #5):

  • 1, 4, 7, 10: Assigned string is “It’s January, April, July, or October”.
  • 2, 5, 8, 11: Assigned string is “It’s February, May, August, or November”.
  • 3, 6, 9, 12: Assigned string is “It’s March, June, September, or December”.
Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        Case 1, 4, 7, 10: MyMonthMessage = "It's January, April, July, or October"
        Case 2, 5, 8, 11: MyMonthMessage = "It's February, May, August, or November"
        Case 3, 6, 9, 12: MyMonthMessage = "It's March, June, September, or December"
    End Select
    
    '...

End Sub

(7) Display a message box (MsgBox) with the value held by the MyMonthMessage variable.

Sub SelectCaseMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        Case 1, 4, 7, 10: MyMonthMessage = "It's January, April, July, or October"
        Case 2, 5, 8, 11: MyMonthMessage = "It's February, May, August, or November"
        Case 3, 6, 9, 12: MyMonthMessage = "It's March, June, September, or December"
    End Select
    
    'Display message box with string held by the MyMonthMessage variable
    MsgBox MyMonthMessage

End Sub

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case multiple values example macro. I execute the example macro (and create this screenshot) during May.

Excel VBA Select Case multiple values example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Select Case Multiple Values vs. If… Then… ElseIf… Multiple Values Example Macro

The following If… Then… ElseIf… multiple values example macro is an equivalent example macro (to the Select Case multiple values example macro I explain above) working with the If… Then… Else statement (vs. the Select Case statement).

Sub SelectCaseMultipleValuesVsIfThenElseIfMultipleValues()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variables to represent:
        '(1) Number representing month
        '(2) Message to be displayed in message box
    Dim MyCurrentMonth As Integer
    Dim MyMonthMessage As String
    
    'Assign number representing month to the MyCurrentMonth variable
    MyCurrentMonth = Month(Date:=Date)
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    If (MyCurrentMonth = 1) Or (MyCurrentMonth = 4) Or (MyCurrentMonth = 7) Or (MyCurrentMonth = 10) Then
        MyMonthMessage = "It's January, April, July, or October"
    ElseIf (MyCurrentMonth = 2) Or (MyCurrentMonth = 5) Or (MyCurrentMonth = 8) Or (MyCurrentMonth = 11) Then
        MyMonthMessage = "It's February, May, August, or November"
    ElseIf (MyCurrentMonth = 3) Or (MyCurrentMonth = 6) Or (MyCurrentMonth = 9) Or (MyCurrentMonth = 12) Then
        MyMonthMessage = "It's March, June, September, or December"
    End If
    
    'Display message box with string held by the MyMonthMessage variable
    MsgBox MyMonthMessage

End Sub

Notice how the Select Case statement results in more efficient VBA code that’s easier to:

  • Read;
  • Follow;
  • Understand; and
  • Work with.

The image below displays the message box shown by Excel when I execute the Excel VBA If… Then… ElseIf… multiple values example macro. I execute the example macro (and create this screenshot) during May.

Excel VBA Select Case vs. If... Then... Else multiple values example macro results


Get immediate free access to the Excel VBA Select Case example workbook

(6) Excel VBA Select Case Multiple Conditions

In this Section, you learn how to create an Excel VBA Select Case statement to conditionally execute a set of statements based on:

  • An expression’s value; and
  • Multiple conditions (grouping several cases inside a single case expression).

Excel VBA Select Case Multiple Conditions Snippet Template/Structure

The following is the Excel VBA Select Case multiple conditions snippet template/structure I explain (step-by-step) in the Sections below.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select

When creating a Select Case multiple conditions statement, each CaseExpression# can follow (as appropriate) one of the following templates/structures:

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/

LowerBoundCase To UpperBoundCase

Is ComparisonOperator ComparisonCase

Case1, Case2, Case3, …, Case#

CaseRange1, CaseRange2, CaseRange3, …, CaseRange#


Get immediate free access to the Excel VBA Select Case example workbook

Step-by-Step Process to Set Up an Excel VBA Select Case Multiple Conditions Statement

Do the following to create an Excel VBA Select Case multiple conditions statement:

(1) Enter the opening and closing statements of the Select Case statement.

  • Select Case.
  • End Select.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case '...
    '...
End Select

(2) Specify the test expression VBA uses to identify the set of statements to execute: TestExpression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    '...
End Select

(3) Specify the case expressions used by VBA to identify the set of statements to execute:

  • CaseExpression1.
  • CaseExpression2.
  • CaseExpression#.

You can (as a general rule) include as many case expressions as required inside a single Select Case statement.

Each case expression is preceded by the Case keyword:

  • Case CaseExpression1.
  • Case CaseExpression2.
  • Case CaseExpression#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        '...
    Case CaseExpression2
        '...
    '...
    Case CaseExpression#
        '...
End Select

When creating a Select Case multiple conditions statement, use the following constructs and structures to group several cases inside a single case expression:

(3.1.) Use the To and Is keywords to specify a range of values or strings for a single case expression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/

'To keyword
LowerBoundCase To UpperBoundCase

'Is keyword
Is ComparisonOperator ComparisonCase

(3.2.) Use commas to separate multiple:

  • Values or strings; or
  • Value or string ranges (usually created by working with the To or Is keywords I explain above);

Inside a single case expression.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/

'Values or strings
Case1, Case2, Case3, …, Case#

'Value or string ranges
CaseRange1, CaseRange2, CaseRange3, …, CaseRange#

The Case keyword plus associated case expression (Case CaseExpression#) form a Case clause.

When the test expression (you specified in step #2) matches an individual case expression, the Select Case statement:

  1. Executes the set of statements (you specify in step #4) associated to the applicable Case clause (whose case expression matched the test expression); and
  2. Exits the Select Case statement.

(4) Specify the set of statements to be executed when the applicable case expression (you specified in step #3) matches the test expression (you specified in step #2).

  • CaseStatements1.
  • CaseStatements2.
  • CaseStatements#.
'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
    '...
End Select

(5) Specify the set of statements to be executed if no case expression (you specified in step #3) matches the test expression (you specified in step #2). These catch-all statements follow the Case Else keyword.

'Source: https://powerspreadsheets.com/
'More information: https://powerspreadsheets.com/excel-vba-select-case/
Select Case TestExpression
    Case CaseExpression1
        CaseStatements1
    Case CaseExpression2
        CaseStatements2
    '...
    Case CaseExpression#
        CaseStatements#
    Case Else
        ElseStatements
End Select


Get immediate free access to the Excel VBA Select Case example workbook

Additional Cues for Excel VBA Select Case Multiple Conditions

(1) The Select Case statement is an alternative to complex If… Then… Else statements (Select Case vs. If… Then… Else). Consider using the Select Case statement when dealing with (more) complex cases.

(2) Consider indenting the statements inside Select Case statements.

(3) Consider working with the separator character (:) to separate:

  • The Case clause (Case CaseExpression#) and the statements to be executed (CaseStatements#); or
  • The Case Else keyword (Case Else) and the catch-all statements (ElseStatements);

When the following 2 conditions are met:

  1. The case results in a single statement (CaseStatement#) being executed or there’s (only) a single catch-all statement (ElseStatement); and
  2. The resulting line of VBA code is not excessively long.

(3) You have a significant degree of flexibility when specifying case expressions inside a Select Case statement. This flexibility includes the possibility to group several cases inside a single case expression (as you learned in this Section).

(4) When using the Is keyword to specify a range of values or strings for a single case expression (Is ComparisonOperator ComparisonCase), ComparisonOperator is a comparison operator, excluding the following operators:

  • Is.
  • Like.

(5) As a general rule: Organize case expressions:

  • By decreasing order of probability.
  • In such a way that any case expression excludes subsequent case expressions.

(6) The Case Else keyword/clause (Case Else: ElseStatements) is optional.

Work with the Case Else clause to specify a set of catch-all statements that are executed when none of the conditions you (originally) expected is met (no case expression matches the test expression).

(7) If:

  • You omit the Case Else clause; and
  • No case expression matches the test expression;

Procedure execution continues with the first statement after the end of the Select Case statement (after “End Select”).


Get immediate free access to the Excel VBA Select Case example workbook

Excel VBA Select Case Multiple Conditions Example Macro

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples inside this Tutorial (including this example). Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

I create the Excel VBA Select Case multiple conditions example macro as follows:

(1) Declare a Sub procedure (SelectCaseMultipleConditions).

Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    '...

End Sub

(2) Declare a variable (MyMonthMessage) of the String data type.

Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    '...

End Sub

(3) Enter the opening and closing statements of the Select Case statement.

Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    Select Case '...
        
        '...
    
    End Select
    
    '...

End Sub

(4) Specify the test expression VBA uses to identify the set of statements to execute.

The test expression I use (Month(Date:=Date)) returns an integer (1 to 12) representing the current month of the year.

Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    Select Case Month(Date:=Date)
        
        '...
    
    End Select
    
    '...

End Sub

(5) Specify the case expressions used by VBA to identify the set of statements to execute.

I use the following constructs and structures to group several cases inside a single case expression:

  • The To and Is keywords to specify a range of values or strings for a single case expression.
  • Commas to separate multiple values or strings.

The test expression I specified in step #4 returns an integer between 1 and 12.

The case expressions I specify (considering the above) are:

  • Is < 7.
  • 7 To 9.
  • 10, 11.
Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    Select Case Month(Date:=Date)
        
        Case Is < 7: '...
        
        Case 7 To 9: '...
        
        Case 10, 11: '...
        
        Case Else: '...
    
    End Select
    
    '...

End Sub

(6) Specify the statement to be executed when the applicable case expression (I specified in step #5) matches the test expression (I specified in step #4).

The statements I use assign a string to the MyMonthMessage variable (I declared in step #2). The assigned string varies, depending on the applicable case expression (I specified in step #5):

  • Is < 7: Assigned string is “It’s H1”.
  • 7 To 9: Assigned string is “It’s Q3”.
  • 10, 11: Assigned string is “It’s Q4, but not yet December”.
Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        
        'If the current month is less than 7, message is "It's H1"
        Case Is < 7: MyMonthMessage = "It's H1"
        
        'If the current month is from 7 to 9, message is "It's Q3"
        Case 7 To 9: MyMonthMessage = "It's Q3"
        
        'If the current month is 10 or 11, message is "It's Q4, but not yet December"
        Case 10, 11: MyMonthMessage = "It's Q4, but not yet December"
        
        '...
    
    End Select
    
    '...

End Sub

(7) Specify the catch-all statement to be executed if no case expression (from the case expressions I specified in step #5) matches the test expression (I specified in step #4).

The statement I use assigns a string to the MyMonthMessage variable (I declared in step #2): “It’s December”.

Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        
        'If the current month is less than 7, message is "It's H1"
        Case Is < 7: MyMonthMessage = "It's H1"
        
        'If the current month is from 7 to 9, message is "It's Q3"
        Case 7 To 9: MyMonthMessage = "It's Q3"
        
        'If the current month is 10 or 11, message is "It's Q4, but not yet December"
        Case 10, 11: MyMonthMessage = "It's Q4, but not yet December"
        
        'If the current month doesn't match any of the previous case expressions, message is "It's December"
        Case Else: MyMonthMessage = "It's December"
    
    End Select
    
    '...

End Sub

(8) Display a message box (MsgBox) with the value held by the MyMonthMessage variable.

Sub SelectCaseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variable to represent message to be displayed in message box
    Dim MyMonthMessage As String
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    Select Case Month(Date:=Date)
        
        'If the current month is less than 7, message is "It's H1"
        Case Is < 7: MyMonthMessage = "It's H1"
        
        'If the current month is from 7 to 9, message is "It's Q3"
        Case 7 To 9: MyMonthMessage = "It's Q3"
        
        'If the current month is 10 or 11, message is "It's Q4, but not yet December"
        Case 10, 11: MyMonthMessage = "It's Q4, but not yet December"
        
        'If the current month doesn't match any of the previous case expressions, message is "It's December"
        Case Else: MyMonthMessage = "It's December"
    
    End Select
    
    'Display message box with string held by the MyMonthMessage variable
    MsgBox MyMonthMessage

End Sub

The image below displays the message box shown by Excel when I execute the Excel VBA Select Case multiple conditions example macro. I execute the example macro (and create this screenshot) during March.

Excel VBA Select Case multiple conditions example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Select Case Multiple Conditions vs. If… Then… ElseIf… Else Multiple Conditions Example Macro

The following If… Then… ElseIf… Else multiple conditions example macro is an equivalent example macro (to the Select Case multiple conditions example macro I explain above) working with the If… Then… Else statement (vs. the Select Case statement).

Sub SelectCaseMultipleConditionsVsIfThenElseIfElseMultipleConditions()
    'Source: https://powerspreadsheets.com/
    'More information: https://powerspreadsheets.com/excel-vba-select-case/
    
    'Declare variables to represent:
        '(1) Number representing month
        '(2) Message to be displayed in message box
    Dim MyCurrentMonth As Integer
    Dim MyMonthMessage As String
    
    'Assign number representing month to the MyCurrentMonth variable
    MyCurrentMonth = Month(Date:=Date)
    
    'Assign a string to the MyMonthMessage variable, depending on the current month
    If MyCurrentMonth < 7 Then
        MyMonthMessage = "It's H1"
    ElseIf (MyCurrentMonth >= 7) And (MyCurrentMonth <= 9) Then
        MyMonthMessage = "It's Q3"
    ElseIf (MyCurrentMonth = 10) Or (MyCurrentMonth = 11) Then
        MyMonthMessage = "It's Q4, but not yet December"
    Else
        MyMonthMessage = "It's December"
    End If
    
    'Display message box with string held by the MyMonthMessage variable
    MsgBox MyMonthMessage

End Sub

Notice how the Select Case statement results in more efficient VBA code that’s easier to:

  • Read;
  • Follow;
  • Understand; and
  • Work with.

The image below displays the message box shown by Excel when I execute the Excel VBA If… Then… ElseIf… Else multiple conditions example macro. I execute the example macro (and create this screenshot) during March.

Excel VBA Select Case vs. If... Then... Else multiple conditions example macro results


Get immediate free access to the Excel VBA Select Case example workbook

Download the Excel VBA Select Case Example Workbook

This Excel VBA Select Case Tutorial is accompanied by an Excel workbook with the data and VBA code I use in the examples above. Get this example workbook (for free) by clicking the button below.


Get immediate free access to the Excel VBA Select Case example workbook

The following Excel Macro and VBA Tutorials may help you better understand and implement the contents above.

  • Tutorials about general macro and VBA constructs and structures:
    • Tutorials for Beginners:
      • Excel Macros: Click here to open.
      • Excel VBA: Click here to open.
    • Enable macros in Excel: Click here to open.
    • Work with the Visual Basic Editor (VBE): Click here to open.
    • Create Sub procedures: Click here to open.
    • Work with:
      • Variables: Click here to open.
      • Data types: Click here to open.
      • Functions: Click here to open.
  • Tutorials with practical VBA applications and macro examples:
    • Excel VBA Change Font Color Based on Cell Value: Click here to open.
    • Create a message box: Click here to open.
    • Create an input box: Click here to open.

This Excel VBA Select Case Tutorial is part of a more comprehensive series of Excel VBA Select Case Tutorials.

  • Excel VBA Select Case Tutorial: Click here to open.
  • Excel VBA Select Case Or: Click here to open.
  • Excel VBA Select Case And Operator: Click here to open.
  • Excel VBA Select Case Multiple Test Expressions: Click here to open.
  • Excel VBA Select Case Like Wildcard: Click here to open.
  • Excel VBA Select Case Inside For… Next Loop: Click here to open.
  • Excel VBA Select Case Range of Cells: Click here to open.

You can find more Excel and VBA Tutorials in the organized Tutorials Archive: Click here to visit the Archives. The following are some of my most popular Excel Tutorials and Training Resources:

  • Excel Keyboard Shortcuts Cheat Sheet: Click here to open.
  • Work with the Excel XLOOKUP Function: Click here to open.
  • Excel Power Query (Get & Transform) Tutorial for Beginners: Click here to open.

If you want to learn how to automate Excel (and save time) by working with macros and VBA, you may be interested in the following Premium Excel Macro and VBA Training Materials:

  • Premium Courses at the Power Spreadsheets Academy: Click here to open.
  • Books at the Power Spreadsheets Library: Click here to open.
  • VBA Cheat Sheets: Click here to open.

If you want to save time when working with macros and VBA, you may be interested in AutoMacro: Click here to learn more about AutoMacro (affiliate link). AutoMacro is an add-in for VBA that installs directly into the VBE. Depending on the version, AutoMacro comes loaded with:

  • Code generators.
  • An extensive code library.
  • The ability to create your own code library.
  • Advanced coding tools.

If you need help with Excel tasks/projects, you may be interested in working with me: Click here to learn more about working with me.


Get immediate free access to the Excel VBA Select Case example workbook

Conditional Statements in Excel VBA

Related Link: If…Then…Else Statements (VBA).

There are primarily two Conditional Statements in VBA: If…Then…Else Statements and Select…Case Statement. In both of these, one or more conditions are evaluated and a block of code is executed depending on the result of the evaluation.

Select…Case Statement (VBA)

If…Then…Else Statements (VBA)

————————————————————————————————

Contents:

Select…Case Statement (VBA)

Syntax

Using the To keyword to specify the upper and lower range of values

Using the Is keyword (with a comparison operator) to compare values

Using a comma to separate multiple expressions or ranges in each Case clause

Option Compare Setting

Nesting

GoTo statement

Select…Case compared to If…Then…Else Statements

————————————————————————————————


Select…Case Statement (VBA)

Executes different blocks of code or statements, depending on the respective condition(s) being met. It evaluates an expression and based on its result executes one of the many set of statements. It is very similar to the If…Then…Else statements.

Syntax

 Select Case expression

Case expression_value_1

statements_1

Case expression_value_n

statements_n

Case Else

else_statements

End Select

expression can be a variable, a field or a range. It can be expresesed using a vba function -> as «IsNumeric(rng)» or «rng.HasFormula», where ‘rng’ is a Range variable. It should evaluate to a Boolean value, String value, Numeric value or Date type ie. to any of the basic data types of Boolean, Byte, Integer, Long, Single, Double, Decimal,  Date, Object, String, Variant, … It is necessary to specify an expression. It is the value of this expression which is tested and compared (with expression_value) in each Case and when it matches, the statements specified in the matching Case are executed.

expression_value  [expression_value_1 … expression_value_n] -> the data type of expression_value should match or be convertible to that of expression. In each Case, the value of the expression is compared to the expression_value, and if a match is found, the specified statements get executed. It is necessary to specify atleast one expression_value. Expression_values are tested in the order they are mentioned. These (expression_value) are like a list of conditions and when a condition is met, the relevant block of code gets executed.

statements  [statements_1 … statements_n] -> statements specified in a particular Case get executed if the value of the expression matches the relevant expression_value of that Case.

Case Else -> expression_values are tested in the order they are mentioned and if a match is found, its respective statements get executed and no subsequent expression_value is tested thereafter. If no match is found for any expression_value, Case Else clause comes into play and the else_statements get executed. It is Optional to have the Case Else clause.

else_statements  ->  these statements get executed if no match is found in any of the expression_values. It is optional to specify else_statements. If a match has not been found in any expression_value and else_statements are not specified also, in this case no code will be executed in the Select…Case Statements block.

End Select  ->  terminates the Select…Case block of statements and it is necessary to mention these keywords at the end.

Example:

Sub selectCase1()
‘making strAge equivalent to «young» will return the message «Less than 40 years»

Dim strAge As String

strAge = «young»

Select Case strAge

Case «senior citizen»

MsgBox «Over 60 years»

Case «middle age»

MsgBox «Between 40 to 59 years»

Case «young»

MsgBox «Less than 40 years»

Case Else

MsgBox «Invalid»

End Select

End Sub

Using the To keyword to specify the upper and lower range of values

Use the To keyword in expression_value to specify the upper and lower range of matching values, as shown below. The value to the left of To keyword should be less than or equal to the value to the right of the To keyword. Range can also be specified for character strings.

Example:

Sub selectCaseTo()
‘entering marks as 69 will return the message «Average»; entering marks as 101 will return the message «Out of Range»

Dim iMarks As Integer

iMarks = InputBox(«Enter marks»)

Select Case iMarks

Case 70 To 100

MsgBox «Good»

Case 40 To 69

MsgBox «Average»

Case 0 To 39

MsgBox «Failed»

Case Else

MsgBox «Out of Range»

End Select

End Sub

Using the Is keyword (with a comparison operator) to compare values

To include a comparison operator (=, <>, <, >, <=, or >=) in expression_value, use the Is keyword. The Is keyword is automatically inserted before a comparison operator, if not specifically included. See below example.

Example:

Sub selectCaseIs()
‘if sngTemp equals 39.5, returned message is «Moderately Hot»

Dim sngTemp As Single

sngTemp = 39.5

Select Case sngTemp

Case Is >= 40

MsgBox «Extremely Hot»

Case Is >= 25

MsgBox «Moderately Hot»

Case Is >= 0

MsgBox «Cool Weather»

Case Is < 0

MsgBox «Extremely Cold»

End Select

End Sub

Using a comma to separate multiple expressions or ranges in each Case clause

Multiple expressions or ranges can be specified in each Case clause, by separating each expression with a comma (which has the effect of the OR operator). Multiple expressions or ranges can also be specified for character strings. See below examples.

Example:

Sub selectCaseMultiple_1()
‘if alpha equates to «Hello», the returned message is «Odd Number or Hello»

Dim alpha As Variant

alpha = «Hello»

Select Case alpha

Case a, e, i, o, u

MsgBox «Vowels»

Case 2, 4, 6, 8

MsgBox «Even Number»

Case 1, 3, 5, 7, 9, «Hello»

MsgBox «Odd Number or Hello»

Case Else

MsgBox «Out of Range»

End Select

End Sub

Example:

In this example, the string comparison «apples» To «grapes» determines a value between «apples» and «grapes» in alphabetical order, and uses the default text comparison method of Binary (which is case-sensitive) because Option Compare Statement is not specified — see below.

Sub SelectCaseMultiple_OptionCompare_NotSpecified()
‘Option Compare is NOT specified and therefore text comparison will be case-sensitive
‘bananas will return the message «Text between apples and grapes, or specifically mangoes, or the numbers 98 or 99»; oranges will return the message «Out of Range»; Apples will return the message «Out of Range».

Dim var As Variant, strResult As String

var = InputBox(«Enter»)

Select Case var

Case 1 To 10, 11 To 20: strResult = «Number is between 1 and 20»

Case «apples» To «grapes», «mangoes», 98, 99: strResult = «Text between apples and grapes, or specifically mangoes, or the numbers 98 or 99»

Case Else: strResult = «Out of Range»

End Select

MsgBox strResult

End Sub

Option Compare Setting:

You can compare string data using string comparison methods of Binary, Text or Database. Database is used only with Microsoft Access.

Option Compare Binary makes string comparisons based on a binary sort order (in Microsoft Windows, the code page determines the sort order — wherein ANSI 1252 is used for English and many European languages) -> A < B < U < Z < a < b < u < z < À < Û < à < û

Option Compare Text makes string comparisons which are not based on a case-sensitive text sort order -> (A=a) < (À = à) < (B=b) < (U=u) < (Û = û) < (Z=z)

Option Compare Statement (viz. Option Compare Binary or Option Compare Text) can be used to set the comparison method. It must be used at the module level, before any procedure. If the Option Compare Statement is not specified, the default text comparison method is Binary.

Example — Option Compare Binary or Default

Option Compare Binary
————————————————————————
Sub OptionCompareBinary_Specified()
‘Option Compare Binary is specified and therefore text comparison will be case-sensitive
‘»Apples» will return the message «Out of Range»; «Grapes» will return «Out of Range» («G» comes before «a» in ANSI code); «gRound» will return «Text between apples and grapes», whereas «ground» is «Out of Range»

Dim str As String

str = InputBox(«Enter text»)

Select Case str

Case «apples» To «grapes»

MsgBox «Text between apples and grapes»

Case Else

MsgBox «Out of Range»

End Select

End Sub

Example — Option Compare Text 

Option Compare Text
———————————————————————-
Sub OptionCompareText_Specified()
‘Option Compare Text is specified and therefore text comparison will NOT be case-sensitive;
‘Both «Apples» and «Grapes» will return the message «Text between apples and grapes»; both «gRound» and «ground» will return «Out of Range»

Dim str As String

str = InputBox(«Enter text»)

Select Case str

Case «apples» To «grapes»

MsgBox «Text between apples and grapes»

Case Else

MsgBox «Out of Range»

End Select

End Sub

Nesting:

Select…Case block of statements can be nested within each other and also with If…Then…Else statements and VBA loops (as inner or outer loop), without any limit. When Select…Case is nested within the other, it must be a complete block and terminate with its own End Select, within a specific Case or Case Else clause of the outer Select…Case block.

Example: (using nested Select…Case statements)

Sub selectCaseNested1()
‘check if a range is empty; and if not empty, whether has a numeric value and if numeric then if also has a formula; and if not numeric then what is the text length.

Dim rng As Range, iLength As Integer

Set rng = ActiveSheet.Range(«A1»)

Select Case IsEmpty(rng)

Case True

MsgBox rng.Address & » is empty»

Case Else

Select Case IsNumeric(rng)

Case True

MsgBox rng.Address & » has a numeric value»

Select Case rng.HasFormula

Case True

MsgBox rng.Address & » also has a formula»

End Select

Case Else

iLength = Len(rng)
MsgBox rng.Address & » has a Text length of » & iLength

End Select

End Select

End Sub

Example: (Text Manipulation with nested Conditional Statements and VBA Loops)

Function StringManipulation(str As String) As String
‘This code customizes a string text as follows:
‘1. removes numericals from a text string;
‘2. removes leading, trailing & inbetween spaces (leaves single space between words);
‘3. adds space (if not present) after each exclamation, comma, full stop and question mark;
‘4. capitalizes the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark;

Dim iTxtLen As Integer, iStrLen As Integer, n As Integer, i As Integer, ansiCode As Integer

‘—————————

‘REMOVE NUMERICALS

‘chr(48) to chr(57) represent numericals 0 to 9 in ANSI/ASCII character codes

For i = 48 To 57

‘remove all numericals from the text string using vba Replace function:

str = Replace(str, Chr(i), «»)

Next i

‘—————————

‘REMOVE LEADING, TRAILING & INBETWEEN SPACES (LEAVE SINGLE SPACE BETWEEN WORDS)

‘use the worksheet TRIM function. Note: the TRIM function removes space character with ANSI code 32, does not remove the nonbreaking space character with ANSI code 160

str = Application.Trim(str)

‘—————————

‘ADD SPACE (IF NOT PRESENT) AFTER EACH EXCLAMATION, COMMA, DOT AND QUESTION MARK:

‘set variable value to string length:

iTxtLen = Len(str)

For n = iTxtLen To 1 Step -1

‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns full stop; Chr(63) returns question mark;

If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then

‘check if space is not present:

If Mid(str, n + 1, 1) <> Chr(32) Then

‘using Mid & Right functions to add space — note that current string length is used:

str = Mid(str, 1, n) & Chr(32) & Right(str, iTxtLen — n)

‘update string length — increments by 1 after adding a space (character):

iTxtLen = iTxtLen + 1

End If

End If

Next n

‘—————————

‘DELETE SPACE (IF PRESENT) BEFORE EACH EXCLAMATION, COMMA, DOT & QUESTION MARK:

‘reset variable value to string length:

iTxtLen = Len(str)

For n = iTxtLen To 1 Step -1

‘Chr(32) returns space; Chr(33) returns exclamation; Chr(44) returns comma; Chr(46) returns full stop; Chr(63) returns question mark;

If Mid(str, n, 1) = Chr(33) Or Mid(str, n, 1) = Chr(44) Or Mid(str, n, 1) = Chr(46) Or Mid(str, n, 1) = Chr(63) Then

‘check if space is present:

If Mid(str, n — 1, 1) = Chr(32) Then

‘using the worksheet Replace function to delete a space:

str = Application.Replace(str, n — 1, 1, «»)

‘omit rechecking the same character again — position of n shifts (decreases by 1) due to deleting a space character:

n = n — 1

End If

End If

Next n

‘—————————

‘CAPITALIZE LETTERS:

‘capitalize the very first letter of the string and the first letter of a word after each exclamation, full stop and question mark, while all other letters are lower case

iStrLen = Len(str)

For i = 1 To iStrLen

‘determine the ANSI code of each character in the string

ansiCode = Asc(Mid(str, i, 1))

Select Case ansiCode

’97 to 122 are the ANSI codes equating to small cap letters «a» to «z»

Case 97 To 122

If i > 2 Then

‘capitalizes a letter whose position is 2 characters after (1 character after, will be the space character added earlier) an exclamation, full stop and question mark:

If Mid(str, i — 2, 1) = Chr(33) Or Mid(str, i — 2, 1) = Chr(46) Or Mid(str, i — 2, 1) = Chr(63) Then

Mid(str, i, 1) = UCase(Mid(str, i, 1))

End If

‘capitalize first letter of the string:

ElseIf i = 1 Then

Mid(str, i, 1) = UCase(Mid(str, i, 1))

End If

‘if capital letter, skip to next character (ie. next i):

Case Else

GoTo skip

End Select

skip:

Next i

‘—————————

‘manipulated string:

StringManipulation = str

End Function

Sub Str_Man()
‘specify text string to manipulate & get manipulated string

Dim strText As String

‘specify the text string, which is required to be manipulated

strText = ActiveSheet.Range(«A1»).Value

‘the manipulated text string is entered in range A5 of the active sheet, on running the procedure:

ActiveSheet.Range(«A5»).Value = StringManipulation(strText)

End Sub

GoTo statement 

Use the GoTo statement to jump to a line within the procedure. The GoTo statement consists of 2 parts: (1) The GoTo statement which is the GoTo keywords followed by a Label which is the identifier; and (2) The Label — this consists of the Name of the Label followed by a colon, and then has a line of code. On satisfying a condition, the GoTo statement transfers control to a separate line of code within the procedure, identified by the Label. GoTo statement is usually avoidable if there is an alternate solution (usually there is — many times you can use If…Then…Else and Select…Case statements alternatively). It makes the code somewhat unreadable and confusing. It is used best for error handling, viz. «On Error GoTo».

For live codes of running Select…Case Statements, click to download excel file.

Select…Case   compared to   If…Then…Else Statements 

Both are Conditional Statements, wherein one or more conditions are evaluated and a block of code is executed depending on the result of the evaluation.

The difference lies in that in a Select…Case statement, a single expression (or variable) is considered and evaluated at a time. The variable to be evaluated is determined in the first line of «Select Case expression», and then multiple Case statements specify the possible values. Whereas in If…Then…Else statements, multiple expressions (or variables) can be considered and evaluated simultaneously. Select…Case statement tests a single item for several possible values, whereas If…Then…Else statements test multiple items for several possible values. In this sense, If…Then…Else statements are more flexible in testing multiple variables for multiple conditions.

In case of a large number of conditions, If…Then…Else statements might get and appear confusing and the code tends to become unreadable.

Like this post? Please share to your friends:
  • Select case vba excel примеры
  • Select all titles in word
  • Select case is not vba excel
  • Select all the text in word
  • Select case for vba excel