If Statement

Syntax

If condexpr Then [instruction] [Else instruction]
-or-
If condexpr Then
statement
s
[ElseIf condexpr Then
statement
s]...
[Else
statement
s]
End
If
-or-
If TypeOf objexpr Is objtype Then ...

Group

Flow Control

Description

Form 1: Single line if statement. Execute the instruction following the Then if condexpr is True. Otherwise, execute the instruction following the Else. The Else portion is optional.

Form 2: The multiple line if is useful for complex ifs. Each if condexpr is checked in turn. The first True one causes the following statements to be executed. If all are False then the Else's statements are executed. The ElseIf and Else portions are optional.

Form 3: If objexpr's type is the same type or a type descended from objtype the Then portion is executed.

See Also: Select Case, Choose( ), IIf( ).

Example

Sub Main
S = InputBox("Enter hello, goodbye, dinner or sleep:")
S = UCase(S)
If S = "HELLO" Then Debug.Print "come in"
If S = "GOODBYE" Then Debug.Print "see you later"
If S = "DINNER" Then
Debug
.Print "Please come in".
Debug
.Print "Dinner will be ready soon".
ElseIf S = "SLEEP" Then
Debug
.Print "Sorry".
Debug
.Print "We are full for the night"
End
If
End Sub