Microsoft Office Development and Consultancy
|VBA > Syntax > If - Then - Else||< Previous | Next >|
Step 1 - What is an If statement ?
This is probably the most common instruction used in most programming langauges and it allows you to include decision making into your program.
If a particular condition is true, then execute this statement(s) otherwise execute this statement(s).
The condition is always a boolean expression that evaluates to either True or False.
This can be used to execute one or more lines conditionally.
You can exit an If statement at any point by using the following line
Step 2 - If - Then
It is common to not include the "= True" part as this is implicit
An alternative is the one line version although a lot of developers avoid this as it is difficult to maintain and can be confusing.
Step 3 - If - Then - Else
The Else clause is optional but can be useful when you want to execute statements for both conditions
If you are only testing for one condition it is common to abbreviate this to one line.
This is not recommended as it makes you code a lot harder to read and also to change at a later date.
Step 4 - Nested If
Nested If statements and long sequences of ElseIf are often hard to read and very hard to debug.
When you have a complex set of choices using the Select-Case statement is a much more appropriate.
Step 5 - ElseIf
This statement allows you to perform a related sequence of Ifs.
If the sirst If evaluates to False, then evaluate the first ElseIf.
The first ElseIf condition that evaluates to True will have its statements executed.
If none of the ElseIf conditions evaluate to True then the final Else is executed.
Rather than use a nested If statement you can often achieve the same logic by using an ElseIf construct.
The following block of code is identical to the nested if (above)
The following block can be used to test conditions on all the options. This is identical to a Select - Case
Step 6 - Hanging Else
Step 7 - Evaluating Conditions
Lets suppose we wanted to run the following code for a negative value of x.
Instead of evaluating the first argument and then returning False all the conditions are executed which results in an error.
This is fixed in Visual Basic 2005.
Step 8 - Things to Remember
If you type EndIf as one word it will be automatically split into 2 for you.
Using logical assigments as opposed to IF statements will also help performance (ie y = (x = 5)).
|© Better Solutions Limited 01-Jun-2013||< Previous | Top | Next >|