If...Then...Else Statement Example

This example shows both the block and single-line forms of the If...Then...Else statement. It also illustrates the use of If TypeOf...Then...Else.

Dim Number, Digits, MyString
Number = 53    ' Initialize variable.
If Number < 10 Then
    Digits = 1
ElseIf Number < 100 Then
' Condition evaluates to True so the next statement is executed.
    Digits = 2
Else
    Digits = 3
End If
    
' Assign a value using the single-line form of syntax.
If Digits = 1 Then MyString = "One" Else MyString = "More than one" 

Use If TypeOf construct to determine whether the Control passed into a procedure is a text box.

Sub ControlProcessor(MyControl As Control)
    If TypeOf MyControl Is CommandButton Then
        Debug.Print "You passed in a " & TypeName(MyControl)
    ElseIf TypeOf MyControl Is CheckBox Then
        Debug.Print "You passed in a " & TypeName(MyControl)
    ElseIf TypeOf MyControl Is TextBox Then
        Debug.Print "You passed in a " & TypeName(MyControl)
    End If
End Sub