About Me

Saturday 21 April 2012

VBScript Select Case

VBScript Select Case

The last two lessons you have read through have covered the basics of using the If Statement and the somewhat more advanced ElseIf Statement in VBScript. This lesson will take it a step further by teaching you how to implement the Select Case statement in VBScript.

VBScript Select Case: Why Use It?

When you need to check for many different cases on one variable you could create a large number of ElseIf statements, but this is actually very inefficient. Without getting to specific, it takes VBScript a great deal of computing power to check all these different ElseIf statements. Also, this kind of coding reduces human readability. Because of these problems another programming method, the Select Case statement, was created to solve this problem.
The downside to this new method is you can only check if a variable is equal to something "=" and not compare it with greater than, less than, etc (>, <, >=, <=).

VBScript Select Case: Creation

A VBScript Select Case statement can be summed up into three main parts.
  • Variable - The variable contains the value which we are trying to determine. Our example will be a variable containing the name of a person.
  • Case Statements - The case statements contain the values we are checking for. Our example will contain a few names, each their own case statement.
  • Case Code Blocks - Each case statement has a block of code associated with it. When its case statement is True then the block of code is executed. Our example will print out a greeting depending on the person's name.
Below is a simple example of a Select Case statement that will write something different to the web browser depending on the name stored in the variable myName.

VBScript Code:

<script type="text/vbscript">
Dim myName
myName = "Charles"
Select Case myName
Case "Bob"
 document.write("Been busy Bob?")
Case "Sara"
 document.write("Seen any slick sunglasses Sara?")
Case "Charles"
 document.write("Did you chuck your chowder Charles?")
End Select

</script>

Display:

Did you chuck your chowder Charles?

VBScript Select Case: Else Case

Just like an If Statement has an optional Else clause, a Select Statement has an optional Else case. When the variable cannot match any of the cases included then the Else case will be used.

VBScript Code:

<script type="text/vbscript">
Dim myName
myName = "supercalifragilisticexpialidocious"
Select Case myName
Case "Bob"
 document.write("Been busy Bob?")
Case "Sara"
 document.write("Seen any slick sunglasses Sara?")
Case "Charles"
 document.write("Did you chuck your chowder Charles?")
Case Else
 document.write("Who are you?")
End Select
</script>

Display:

Who are you?

0 comments:

Post a Comment