Contents

# If...Then...Else Statement

Defines one or more statement blocks that you only want to execute if a given condition or expression is True.

### Syntax:

      If condition Then
          statements
      [{ElseIf} condition Then
          statements]
      [Else
          statements]
      {EndIf|End If}

Instead of End If you can write EndIf.

If statements can be shortened to one line when using single statement blocks.

      If condition Then statement [Else statement]

### Parameters:

The If...Then statement executes program blocks depending on given conditions. When LibreOffice Basic encounters an If statement, the condition is tested. If the condition is True, all subsequent statements up to the next Else or ElseIf statement are executed. If the condition is False, and an ElseIf statement follows, LibreOffice Basic tests the next expression and executes the following statements if the condition is True. If False, the program continues either with the next ElseIf or Else statement. Statements following Else are executed only if none of the previously tested conditions were True. After all conditions are evaluated, and the corresponding statements executed, the program continues with the statement following EndIf.

You can nest multiple If...Then statements.

Else and ElseIf statements are optional.

You can use GoTo and GoSub to jump out of an If...Then block, but not to jump into an If...Then structure.

### Example:

The following example enables you to enter the expiration date of a product, and determines if the expiration date has passed.

    Sub ExampleIfThenDate
        Dim sInput As String
        Dim dInput As Date

      On Error Goto inputError
        sInput = InputBox("Enter the expiration date (YYYY-MM-DD)")
        dInput = DateValue(sInput)

        If dInput < Date() Then
            MsgBox "The expiration date has passed"
        ElseIf dInput > Date() Then
            MsgBox "The expiration date has not yet passed"
        Else
            MsgBox "The expiration date is today"
        End If

    inputError:
        If dInput = 0 Then MsgBox "Invalid input"
    End Sub

Related Topics

Select Case statement

Iif or Switch functions

Please support us!