MS-Access / Getting Started

If...Then...Else Statement

Use an If...Then...Else statement to conditionally execute statements based on the evaluation of a condition.

Syntax

If <condition1> Then
    [<procedure statements 1>]
[ElseIf <condition2> Then
    [<procedure statements 2>]]...
[Else
    [<procedure statements n>]]
End If

or

If <condition> Then <thenstmt> [Else <elsestmt>]

Notes

Each condition is a numeric or string expression that Visual Basic can evaluate to True (nonzero) or False (0 or Null). A condition can also consist of multiple comparison expressions and Boolean operators. In addition, a condition can also be the special TypeOf...Is test to evaluate a control variable. The syntax for this test is

TypeOf <Object> Is <ObjectType>

where <Object> is the name of an object variable and <ObjectType> is the name of any valid object type recognized in Access. A common use of this syntax is to loop through all the controls in a form or report Controls collection and take some action if the control is of a specific type (for example, change the FontWeight property of all labels to bold). Valid control types are Attachment, BoundObjectFrame, CheckBox, ComboBox, CommandButton, CustomControl, Image, Label, Line, ListBox, ObjectFrame, OptionButton, OptionGroup, PageBreak, Rectangle, Subform, TabControl, TextBox, and ToggleButton.

If the condition is true, Visual Basic executes the statement or statements immediately following the Then keyword. If the condition is false, Visual Basic evaluates the next ElseIf condition or executes the statements following the Else keyword, whichever occurs next. The alternative syntax does not need an End If statement, but you must enter the entire If... Then statement on a single line. Both <thenstmt> and <elsestmt> can be either a single Visual Basic statement or multiple statements separated by colons (:).

Example

To set an integer value depending on whether a string begins with a letter from A through F, from G through N, or from O through Z, enter the following:

Dim strMyString As String, strFirst As String, _
    intVal As Integer
' Grab the first letter and make it upper case
strFirst = UCase(Left(strMyString, 1))
If strFirst >= "A" And strFirst <= "F" Then
    intVal = 1
ElseIf strFirst >= "G" And strFirst <= "N" Then
    intVal = 2
ElseIf strFirst >= "O" And strFirst <= "Z" Then
    intVal = 3
Else
    intVal = 0
End If
[Previous] [Contents] [Next]