Page 115 - Open Soource Technologies 304.indd
P. 115
Unit 5: VB String and Operators
Case 3:
MsgBox (“Your input is getting pretty big now...”)
Case 4 to 10:
MsgBox (“You are approaching the maximum!”)
Case Is > intMax:
MsgBox (“Too big, sorry.”)
Case Else:
MsgBox (“Please try again.”)
End Select
5.2.8 Making Selections With Switch() And Choose()
For some reason, few books on Visual Basic cover the Switch() and Choose() functions. They
certainly have their uses, however, and we’ll take a look at them here.
The Switch() Function The Switch() function evaluates a list of expressions and returns a Variant
value or an expression associated with the first expression in the list that is true. Here is the syntax:
Switch (expr-1, value-1[, expr-2, value-2 ... [, expr-n, value-n]])
In this case, expr-1 is the first expression to evaluate; if true, Switch() returns value-1. If expr-1 is
not True but expr-2 is, Switch() returns value-2 and so on.
Here is an example showing how to use Switch(). In this case, we ask the user to enter a number
and use Switch() to calculate the absolute value of that value (having temporarily forgotten how
to use the built-in Visual Basic absolute value function, Abs()):
Dim intValue
intValue = InputBox(“Enter a number”)
intAbsValue = Switch(intValue < 0, -1 * intValue,
intValue >= 0, intValue)
MsgBox “Absolute value = “ & Str(intAbsValue)
5.2.9 The Choose() Function
You use the Choose() function to return one of a number of choices based on an index. Here is
the syntax:
Choose (index, choice-1 [, choice-2, ... [, choice-n]])
If the index value is 1, the first choice is returned, if index equals 2, the second choice is returned,
and so on.
Here is an example using Choose(). In this case, we have three employees Bob, Denise, and Ted
with employee IDs 1, 2, and 3. This code snippet accepts an ID value from the user and uses
Choose() to display the corresponding employee name:
Dim intID
intID = -1
LOVELY PROFESSIONAL UNIVERSITY 109