If...Then...Else (statement)

Syntax 1 If condition Then statements [Else else_statements]
Syntax 2 If condition Then   [statements] [ElseIf else_condition Then   [elseif_statements]] [Else   [else_statements]] End If
Description Conditionally executes a statement or group of statements.
Comments The single-line conditional statement (syntax 1) has the following parameters:
Parameter Description
condition Any expression evaluating to a Boolean value.
statements One or more statements separated with colons. This group of statements is executed when condition is TRUE.
else_statements One or more statements separated with colons. This group of statements is executed when condition is FALSE.
The multiline conditional statement (syntax 2) has the following parameters:
Parameter Description
condition Any expression evaluating to a Boolean value.
statements One or more statements to be executed when condition is True .
else_condition Any expression evaluating to a Boolean value. The else_condition is evaluated if condition is False .
elseif_statements One or more statements to be executed when condition is False and else_condition is True .
else_statements One or more statements to be executed when both condition and else_condition are False .
There can be as many ElseIf conditions as required.
Example This example inputs a name from the user and checks to see whether it is MICHAEL or MIKE using three forms of the If...Then...Else statement. It then branches to a statement that displays a welcome message depending on the user's name.
Sub Main()
  uname$ = UCase(InputBox("Enter your name:","Enter Name"))
  If uname$ = "MICHAEL" Then GoSub MikeName
  If uname$ = "MIKE" Then
    GoSub MikeName
    Exit Sub
 End If
 If uname$ = "" Then
    MsgBox "Since you don't have a name, I'll call you MIKE!"
    uname$ = "MIKE"
    GoSub MikeName
  ElseIf uname$ = "MICHAEL" Then
    GoSub MikeName
  Else
    GoSub OtherName
  End If
  Exit Sub
MikeName:
  MsgBox "Hello, MICHAEL!"
  Return
                           
OtherName:
  MsgBox "Hello, " & uname$ & "!"
  Return
End Sub
See Also Choose (function); Switch (function); IIf (function); Select...Case (statement).