|
If...Then...Else Conditional Statements
Rodney POWELL
Microsoft MVP - Excel |
|
Decision Structures in VBA test conditions and then execute code segments
depending on the test's results. This includes a familiar If...
statement.
There are various forms of the If... construct. A single-line
syntax is often used when only one statement is to be executed upon a
successful test condition. It looks like this:
If condition Then statement1 [ Else statement2 ]
The example below will set the SalesTax variable to .0825 if the
condition is True ( CustomerState is "TX" ); otherwise,
the SalesTax variable will be set to 0 (zero).
If CustomerState="TX" Then SalesTax=.0825 Else SalesTax=0
Notice there's no End If used in the single line statement above.
The multi-line (or block) syntax will be easier to read if your
decision structure has numerous conditions.
If condition Then
statement1
[ ElseIf
statement2 ]
[ Else
statement3 ]
End If
Notice this example uses ElseIf to include additional conditions,
and it DOES require an End If.
If CustomerState="TX" Then
SalesTax=.0825
ElseIf CustomerState="VA" Then
SalesTax=.0615
Else
SalesTax=0
End If
In this construct, the program goes through the conditions until it
finds one that is True. Even if there are actually multiple True
conditions, only the FIRST condition that evaluates
as True will be executed. If none of the conditions are satisfied, there is an
optional Else available as a catch all if you need it.
And, finally, here is one more example that shows how you can also
nest conditional statements within other If... statements.
If CustomerState="TX" Then
If CustomerCity="Houston" Then
SalesTax=.0835
ElseIf CustomerCity="Dallas" Then
SalesTax=.0865
Else
SalesTax=.0825
End if
ElseIf CustomerState="VA" Then
If CustomerCity="Virginia Beach" Then
SalesTax=.0675
ElseIf CustomerCity="Vienna" Then
SalesTax=.0685
Else
SalesTax=.0615
End if
Else
SalesTax=0
End If
In an event-driven application, it's important to be able to handle
user feedback and make decisions on how to branch program control based
on a given condition.
Got a suggestion to make this VBA tip more helpful?
Let me know.
|
|
|
|