Page 104 - Excel Progamming Weekend Crash Course
P. 104
h540629 ch06.qxd 9/2/03 9:33 AM Page 79
Session 6 — Control Constructs 79
In another variant, there is an Else clause and two blocks of statements:
If condition Then
block1
Else
block2
End If
If condition is True, the statements in block1 are executed. If it is False, block2 is
executed. One of the two blocks is always executed.
The final variant of the If statement lets you check multiple conditions using the
ElseIf keyword. The syntax is:
If condition-1 Then
block-1
ElseIf condition-2 Then
block-2
...
ElseIf condition-n Then
block-n
Else
block-else
End If
When this is encountered during execution, each condition is tested, starting at the top.
The block associated with the first true condition is executed; then execution passes to the
code after the End If statement. If no condition is true, the block associated with the Else
keyword is executed. The Else keyword and its associated block are optional. If omitted,
there is the possibility that no code within the If...End If structure will be executed.
The short program in Listing 6-1 demonstrates the use of If.
Listing 6-1 Demonstration of the If statement
Public Sub IfDemo()
Dim num
num = InputBox(“Enter a number between 5 and 10:”)
If num < 5 Then
MsgBox(“That’s too small.”)
ElseIf num > 10 Then
MsgBox(“That’s too large.”)
Else
MsgBox(“Thank you!”)
End If
End Sub
When you have more than a few conditions to test, the Select Case statement is usu-
ally a better choice than using a lot of ElseIfs. Either will work, but a Select Case almost
always requires less programming effort.