Conditional Statements

One of the fundamental elements of programming is making decisions based on inputs. Visual Basic provides the If statement for making either/or decisions and the Select statement for making multiple-choice decisions. These two statements form the core of any logic your program uses to adjust to different conditions, and for that reason they are called conditional statements .

The If statement has several different forms:

  • A very simple one-line form:

        If IsArray(Selection) Then MsgBox "Multiple cells selected."
  • A block form that can contain multiple lines and alternative actions:

        Dim str As String
        If IsArray(Selection) Then
            str = "Grand total: " & _
              WorksheetFunction.Sum(Selection)
        Else
            str = "Please select more than one cell"
        End If
        MsgBox str
  • A block form with multiple conditions and alternate actions:

        If IsArray(Selection) Then
            str = "Grand total: " & _
              WorksheetFunction.Sum(Selection)
        ElseIf TypeName(ActiveSheet) = "Worksheet" Then
            str = "Worksheet total: " & _
              WorksheetFunction.Sum(ActiveSheet.UsedRange)
        Else
            str = "Please select a worksheet"
        End If
        MsgBox str

You can have multiple ElseIf statements within an If block as shown by the following general form:

    If condition Then
        ' Do something
    [ElseIf condition Then
        ' Do something else]
    [ElseIf condition Then
        ' Can repeat ElseIf]
    [Else
        ' Do something else]
    End If

For more complex logic, you can include If statements within an enclosing If statement, or you can use the Select Case statement. The following ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.