Page 114 - Open Soource Technologies 304.indd
P. 114
Event Driven Programming
intInput = InputBox(“Enter a positive number”)
Wend
If intInput = 1 Then
MsgBox (“Thank you”.)
ElseIf intInput = 2 Then
MsgBox (“That’s fine”.)
ElseIf intInput >= 3 Then
MsgBox (“Too big”.)
End If
5.2.7 Using Select Case
You have to get a value from the user and respond in several different ways, but you don’t look
forward to a long and tangled series of If&Then&Else statements. What can you do?
If your program can handle multiple values of a particular variable and you don_t want to stack
up a lot of If&Else statements to handle them, you should consider Select Case. You use Select
Case to test an expression, seeing which of several cases it matches, and execute the corresponding
code. Here is the syntax:
Select Case testexpression
[Case expressionlist-n
[statements-n]] ...
[Case Else
[elsestatements]]
End Select
Here is an example using Select Case. In this example, we read a positive value from the user
and test it, responding according to its value. Note that we also use the Select Case Is keyword
(not the same as the Is operator) to check if the value we read in is greater than a certain value,
and Case Else to handle values we don’t explicitly provide code for. Here is the example:
Dim intInput
intInput = –1
While intInput < 0
intInput = InputBox(“Enter a positive number”)
Wend
Const intMax = 100
Select Case intInput
Case 1:
MsgBox (“Thank you”.)
Case 2:
MsgBox (“That’s fine”.)
108 LOVELY PROFESSIONAL UNIVERSITY