|
|
Excel VBA Tutorial Part 5: VBA Conditional Statements
The If ... Then statement tests a condition and if it evaluates to true, carries out a set of actions. Alternative actions can be specified if the condition evaluates to false. The format of the If ... Then statement is: The main Excel VBA Conditional Statements are the If ... Then statement and the Select Case statement. Both of these evaluate one or more conditions and, depending on the result, execute specific actions. The two Conditional Statement types are discussed individually below. The Visual Basic If ... Then StatementThe If ... Then statement tests a condition and if it evaluates to true, carries out a set of actions. Alternative actions can be specified if the condition evaluates to false. The format of the If ... Then statement is:
In the above if statement, the ElseIf and the Else parts of the conditional statement can be left out if desired. The example below shows the If ... Then statement being used to color the current active cell, depending on the value of the cell contents.
The Visual Basic Select Case StatementThe Select Case statement is similar to the If ... Then statement, in that it tests an expression, and carries out different actions, depending on the value of the expression. The format of the Select Case statement is:
In the above code block, the Case Else part of the conditional statement is optional. The example below shows the Select Case statement being used to color the current active cell, depending on the value of the cell contents.
The above example illustrates different ways of defining the different Cases in the Select Case statement. These are:
Note that as soon as one case in the Select Case statement is matched, and the corresponding actions executed, the whole Select Case statement is exited. Therefore, you will never get entry into more than one of the listed cases. |
||||||||||||||
|
|
Copyright © 2008-2011 ExcelFunctions.net |