Download Practice Workbook
Using the sample dataset below, we will illustrate two examples to use the Select Case statement in Excel VBA. This statement is an alternative to the IF-ELSE statement.
Example 1 – Apply CommandButton to Use Select Case
Steps:
- Go to the Developer tab.
- Select Insert.
- Choose the command button from ActiveX Controls.
- Draw a CommandButton.
- Right-click your mouse.
- In the Context menu, select view code.
Private Sub CommandButton1_Click()
Dim Mark As Integer, Grade As String
Mark = Range("C11").Value
Select Case Mark
Case Is >= 90
Grade = "A"
Case Is >= 80
Grade = "B"
Case Is >= 70
Grade = "C"
Case Is >= 60
Grade = "D"
Case Else
Grade = "F"
End Select
Range("C12").Value = Grade
End Sub
Code Explanation:
- We have created two variables Mark and Grade using the dim statement.
- The Mark variable is Integer and the Grade is String.
- We entered the marks in C11.
- We have set Mark as our Case and applied the conditions.
- Go back to the dataset.
- Enter a mark. (For example, 94)
- Select the command button.
- Excel will determine the grade.
Read More: How to Open Workbook from Path Using Excel VBA (4 Examples)
Similar Readings
- How to Write VBA Code in Excel (With Easy Steps)
- Types of VBA Macros in Excel (A Quick Guide)
- Introduction to VBA Features and Applications
- What You Can Do with VBA (6 Practical Uses)
Example 2 – Insert InputBox and MsgBox to Use Select Case
Steps:
- Go to the Developer tab.
- Select Visual Basic.
- The Visual Basic window will open.
- Go to Insert.
- Select Module.
- Excel will create a new module. Enter the following code into the module.
Sub Select_Case_Statement()
Dim Mark As Integer
Dim Grade As String
Mark = InputBox("Enter Mark")
Select Case Mark
Case Is >= 90
Grade = "A"
Case Is >= 80
Grade = "B"
Case Is >= 70
Grade = "C"
Case Is >= 60
Grade = "D"
Case Else
Grade = "F"
End Select
MsgBox "The Student got : " & Grade
End Sub
- Press F5 to run the code.
- Excel will show the following input box.
- Enter any number.
- Click OK.
- Excel will show the grade in a message box.
Read More: Learn Excel VBA Programming & Macros (Free Tutorial – Step by Step)
Things to Remember
- The Select Case statement is an alternative to the IF-ELSE
- You can press ALT+F11 to get the Visual Basic Window.
- Activate Design Mode to edit the command button.
Related Articles
- How to Use Excel VBA User Defined Function in Formula
- 6 Best Excel VBA Programming Books (For Beginners & Advanced Users)
- How to Use VBA Input Function in Excel (2 Examples)
- 22 Macro Examples in Excel VBA
- 20 Practical Coding Tips to Master Excel VBA