Conditionally executes a group of statements, depending on the value of an expression.
If condition Then [statements] [ElseIf condition-n Then [Else End If |
The If...Then...Else statement syntax has these parts:
Part | Description |
condition | Required. Expression that is True or False. |
statements | Optional. One or more statements that are executed if condition is True. |
condition-n | Optional. Same as condition. |
elseifstatements | Optional. One or more statements executed if associated condition-n is True. |
elsestatements | Optional. One or more statements executed if no previous condition or condition-n expression is True. |
The If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The If block must end with an End If statement.
The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a If block, but none can appear after an Else clause. If statements can be nested; that is, contained within one another.
When executing a If block, condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.
Tip Select Case may be more useful when evaluating a single expression that has several possible actions.
This example illustrates the use of the If...Then...Else statement.
Dim Number As Integer, Digits As Integer Number = InputBox("Enter a number (0-999):") ' Initialize variable. If Number < 10 Then Digits = 1 ElseIf Number < 100 Then Digits = 2 Else Digits = 3 End If Trace Digits |
See Also |
Select Case Statement |