If Then statements can be included in your macros to allow certain actions to be taken based on the results of tests that you specify. If Then statements are called conditional statements because they allow you to control the program flow based on logical conditions that you establish.
The basic structure of an If Then statement is as follows.
If condition evaluates to true Then statement
Here is an example.
If myValue = 100 Then cellValue = myValue + 50
This statement tests the condition, myValue = 100. If the variable myValue does equal 100, the variable cellValue will be assigned the value of myValue + 50. If myValue does not equal 100, the statement following the keyword Then will not be executed, and the program will continue with the statement on the next line.
If you have a situation where you need to perform multiple statements if the condition is true, you should structure the If Then as follows.
If condition Then Statement 1 Statement 2 Statement 3 End If
If the condition is true, statements, 1, 2, and 3 will be executed. If the condition is false, the group of statements will not be executed, and the macro will continue at the statement following the End If statement. If you have multiple statements to execute when your If Then condition is true, always use the End If keywords to signify the end of the statements.
If you want to specify a group of statements to perform if the condition is false, use the If Then Else form of the statement.
If condition Then Statement 1 Statement 2 Statement 3 Else Statement 4 Statement 5 Statement 6 End If
In this case, if the condition is true, statements 1, 2, and 3 will be executed, and statements 4, 5, and 6 will be skipped. If the condition is false, statements 1, 2, and 3 will be skipped, and statements 4, 5, and 6 will be executed.
All of the logical operators in the following list can be used in conditional statements.
· Not Inverses a logical value i.e. Not True equals False, and Not False equals True
· = Tests for equality i.e. X = Y will evaluate to true if X has the same value as Y
· <> Not equals i.e. X <> Y will evaluate to true if X does not equal Y
· < Less than i.e. X < Y evaluates to true if X is less than Y
· > Greater than i.e. X > Y evaluates to true if X is greater than Y
· >= Greater than or equal to i.e. 5 >= 5 is true 5 >= 6 is false
·
<= Less
than or equal to i.e. 5 <= 5 is true 5 <= 4 is false |