UserInput = InputBox("Please enter a number between 1 and 100")
#VISUAL BASIC CASE STATEMENTS CODE#
The below code asks for an input and shows a message box based on the value. In Select Case, you can also check for a range of numbers. MsgBox "You entered a number less than 100"Įnd Sub Example 4 – Using a Range of Numbers Instead of the second case with a condition, you can also use Case Else.Ĭase Else acts as a catch-all and anything which doesn’t fall into any of the previous cases is treated by the Case Else.īelow is an example code where I have used Case Else: Sub CheckNumber() In the above example, I used two conditions (less than 100 or greater than or equal to 100). MsgBox "You entered a number more than (or equal to) 100"Įnd Sub Example 3 – Using Case Else to Catch All UserInput = InputBox("Please enter a number") The below code checks whether the input number is greater than 100 or not. You can use an IS condition with the Select Case construct to check for the value of numbers. Example 2 – Using Select Case with IS Condition But as I mentioned, my intent here is to showcase how Select Case works. For example, if you enter 6 or any string, it would do nothing. Note that this code is far from useful and is not even foolproof. UserInput = InputBox("Please enter a number between 1 and 5") 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. Let’s start with a simple example of see how Select Case allows us to check for conditions. These may or may not be the best way to get the work done. Note that most of the examples in this tutorial are meant to explain the concept.
#VISUAL BASIC CASE STATEMENTS HOW TO#
Now to better understand how to use Select Case statement in VBA, let’s go through a few examples. 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. Note: As soon as a condition is met, VBA exits the select case construct. If it meets the condition, then the code block for the given condition is executed.įor every Select Case statement that you use, you need to use the End Select statement.