Using Multiple ifThen Else Statements

There is a third syntax for the if...Then...Else statement that lets you string together as many logical tests as you need:

If condition1 Then

[condition1 TrueStatements] ElseIf condition2 Then

[condition2 TrueStatements] <etc.> Else

[FalseStatements] End If condition1 A logical expression.

condition1 TrueStatements The statements to run if condition1 returns True. condition2 A different logical expression.

condition1 TrueStatements The statements to run if condition2 returns True. FalseStatements The statements to run if both condition1 and condition2 return False.

VBA first tests condition1. If this returns True, VBA runs the group of statements between If...Then and ElseIf...Then. If it returns False, VBA then tests condition2. If this test is True, VBA runs the group of statements between ElseIf...Then and Else. Otherwise, VBA runs the statements between Else and End If. Here are two things you should note about this structure:

■ You can have as many ElseIf conditions as you need.

■ You don't have to use the Else part if you don't need it.

Listing 6.4 shows FutureValue3, a revised version of FutureValue that makes allowances for an improper Frequency argument.

0 0

Post a comment