Open In App

How to Use Select Case Statement in Excel VBA?

Improve
Improve
Like Article
Like
Save
Share
Report

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

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

Select Case Statement of Excel VBA

The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it’s like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it’s like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome.

Syntax of the Select Case Statement of Excel VBA

The VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps determine the course of action based on different cases or scenarios. The structure of the Select Case Statement in Excel VBA follows a particular syntax:

Select [Case] Expression for testing

[Case] List of Expression Statement (Case 1, Case 2, Case 3, ….)

Case Else (Else Statements)

End Select

Arguments:

Expression for Testing:

This single expression is compared against various cases. It can be a numeric or textual expression, including characters, integers, boolean, objects, and strings.

List of Expressions:

This comprises the Case statement against which the “Expression for testing” is evaluated. Excel VBA seeks an exact match within these Case Statements. Each Case Statement contains one or more potential outcomes( values for conditions) that may or may not align with the “Expression for testing.” When multiple expressions/Values exist within a single case, they should be separated by commas.

  • The ‘To’ keyword is used for specifying a range for values within a case statement. The Value before ‘To’ should be less than or equal to the value after it.
  • The ‘Is’ keyword is employed when introducing a logical operator( =,<>,<,>,><= or >=) within case statement. This keyword comes before the logical operator.

Statements:

These are one or more lines of code that comes after the “list of expressions.” Only the code corresponding to the machine Case Statement is executed.

Case Else Statement:

This Closes the Select Case Structure. Every Select Case statement must be accompanied by an End Select statement.

While the “expression for testing,” “list of Expressions” , and End Select sections are mandatory in a Select Case Structure, the “Statements” and Case Else statements are optional components within the provided syntax.

How to use the Select Case Statement of Excel VBA

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

Step 1: Add Developer Tab

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

  • Right-click on any of the existing tabs at the top of the Excel window.
  • Now select Customize the Ribbon from the pop-down menu.In the Excel Options Box, check the box Developer to enable it and click on OK.

select-case0-(1)

Right click on any tab

selectcase2

Click on developer tab

Now, the Developer Tab is visible.

selectcase3

Developer tab

Step 2: Click on Visual Basic and Create a New Module

Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement.

Developer -> Visual Basic -> Tools -> Macros

selectcase1

click on visual basic

Step 3: Create a Macro

After this you can now create a Macro and give it any suitable name you want. It will be better if you choose a name which is related to the project to avoid any confusion.

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

selectcase4

Tools> Macros> Write macro name

selectcase5-(1)

editor window

Select Case Statement

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

Select Case Expression/Condition

Case Val_1

Block of statements when Expression matches Val_1

Case Val_2

Block of statements when Expression matches Val_2

Case Val_3

Block of statements when Expression matches Val_3

.

.

.

Case Else

Block of code when none of the above conditions match

End Select

Val_1, Val_2,… are the values.

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

  • Case Is: It is basically used with numbers.

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

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

Example 1 :

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

Code :

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

selectcaseexample1

Example

selectcase-example11

change in Grade sction

Now, change the marks of the Grade wiill be displayed as “S”.

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

Sub Select_Case_Grade()

‘Declaring variables to fetch marks and store the grade

Dim marks As Integer, Grade As String

‘Fetching marks from the Excel cell

marks = Range(“A2”).Value

Select Case marks

Case 91 To 100

Grade = “S”

Case 81 To 90

Grade = “A”

Case 71 To 80

Grade = “B”

Case 61 To 70

Grade = “C”

Case 51 To 60

Grade = “D”

Case 40 To 50

result = “E”

Case Else

Grade = “F”

End Select

‘Displaying the grade in the Excel cell

Range(“B2”).Value = Grade

End Sub

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

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

selectcaseexample12

user can input data

Sub Select_Case_Allocate()’Declaring variables to fetch marks and store the gradeDim Age As Integer’Asking the user to enter the ageAge = InputBox(“Enter Your Age:”)Select Case (Age Mod 2) = 0 Case True MsgBox “You will work in the morning shift” Case False MsgBox “You will work in the night shift”End SelectEnd Sum

selectcaseexample2

example

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

Code :

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

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

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

selectcaseexample3

example

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

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

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

selectcaseexample4

example

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

FAQs Select Case Statement in Excel VBA

What is Select Case Statement in Excel VBA?

The Select Case Statement in Excel VBA is a versatile tool for making decisions based on multiple conditions. It allows you to compare a single expressions against a list of possible values and execute specific code based on the Matched Value.

What is the Syntax of Select Case Statement look in Excel VBA?

The Basic Syntax of the Select Case Statement in Excel VBA is as follows:

Select Case Expression

Case Value1

‘Code to execute for Value1

Case Value 2

‘Code to execute for Value

Case Else

‘ Code to execute if no Case matches

End Select

Can we use non-numeric values in Select Case Statement?

Yes, The Select Case Statement in Excel VBA supports both numeric and non-numeric values. You can compare strings, dates, Boolean values, and other data types in addition to numbers.

How do I use the Case Else Statement?

The Case Statement is optional and serves as a default case. If none of the specified Case statement matches the Expression, the code within the Case Else block will be executed. This is helpful for handling scenarios where no specific match is found.



Last Updated : 05 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads