Tambien hay una version en castellano de este post, click aca.
Welcome to this post, today we’ll talk about another conditional.
This is similar to if but no evaluate a condition but it takes a variable and evaluates the possible value that can take. Let’s watch how is its syntax:
select case variable
case value_1
... statements ...
case value_2
... statements ...
...
case value_N
... statements ...
case else
... statements ...
end select
Always starts with select case followed by the variable to evaluate. Then, through the use of case we evaluate each possible value for the variable. If the value matches executes the statements until next case. We can use all the cases we need. The final case always is else and it’s used to execute statements if the above cases not match with some value. This final case is optional. Before we study the select case, let’s take the example of the precedent post:
dim rta
rta = inputbox("Do you want to continue (Y/N)?")
if rta = "y" or rta = "Y" then
msgbox "Thanks!"
elseif rta = "n" or rta = "N" then
msgbox "See ya later"
else
msgbox "You can use only Y or N"
end if
This code asks about input a letter to continue or finish the program. This uses to if statement to evaluate the two possible values that we can input and we use an else to warns that we can input only those values. Let’s convert this code to select case:
dim rta
rta = inputbox("Do you want to continue (Y/N)?")
select case rta
case "y"
msgbox "Thanks!"
case "Y"
msgbox "Thanks!"
case "n"
msgbox "See ya later"
case "N"
msgbox "See ya later"
case else
msgbox "You can use only Y or N"
end select
In this code, we change the if statement with select statement. We use the variable that receives the value and we evaluate every possible value through case. In each case we pass the different valid letters that we can receive. In each one, we’ve its respective message and case else it’s for when we don’t have the correct letters. Let’s watch how it works:
On the video, we can watch how it respondes to each input that make in the inputbox. It works in the same way that the original code. But what is the difference between select case and if? Well, when we work with if it’ll pass in every block even we match the value but with select case once it matches the value it outs from the statement. This act can save computer cycles and make our code a little faster.
But remember, select case doesn’t replace to if. They complement between them.
In summary, we talked about select case, how it is, how it works, differences with if, and a little example to watch how it works. I hope you’ve found it useful. You can follow me on this social networks:


Donatión
It’s for site maintenance, thanks!
$1.50
