JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Making Selections with Switch and Choose

For some reason, few books on Visual Basic cover the Switch and Choose functions, but they certainly have their uses and we'll take a look at them here.

Main Page

The Switch Function

The Switch function evaluates a list of expressions and returns an Object value or an expression associated with the first expression in the list that is true. Here's 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's an example showing how to use Switch. In this case, I'm using Switch to calculate the absolute value of the value in the variable intValue (having temporarily forgotten how to use the built-in Visual Basic absolute value function, Abs):

intAbsValue = Switch(intValue < 0, -1 * intValue, intValue >= 0, intValue)

Using the negation operator, -, you can write -1 * intValue simply as -intValue.

Main Page

The Choose Function

You use the Choose function to return one of a number of choices based on an index. Here's 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's an example using Choose. In this case, we have three employees, Bob, Denise, and Ted, with employee IDs 1, 2, and 3. This code uses an ID value to assign the corresponding employee name to strEmployName:

strEmployeeName = Choose(intID, "Bob", "Denise", "Ted")
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor