If...Then...Else Statement

定義一個或多個陳述式區塊,僅當給定條件為 True (真) 時才執行這些陳述區塊。

語法

If condition=true Then Statement block [ElseIf condition=true Then] Statement block [Else] Statement block EndIf

不寫成 Else If,而寫成 ElseIf;不寫成 End If,而寫成 EndIf。

參數:

If...Then 陳述式依給定的條件來執行程式區塊。當 LibreOffice Basic 遇到 If 陳述式時,首先會測試其條件。如果條件為 True (真),則執行所有後續陳述式,直至遇到下一個 ElseElseIf 陳述式。如果條件為 False (假),並且後面有 ElseIf 陳述式,則 LibreOffice Basic 會測試下一個條件,如果為 True (真),則執行其後的陳述式。如果仍為 False (假),程式將繼續測試下一個 ElseIfElse 陳述式。僅當測試的條件全部為 False (假) 時,才會執行 Else 後面的陳述式。演算完所有條件並執行了相應的陳述式之後,程式將繼續執行 EndIf 後面的陳述式。

If...Then 陳述式可以多層嵌套。

ElseElseIf 陳述式是可選擇的。

警告圖示

您可以使用 GoToGoSub 跳出 If...Then 區塊,但是不能跳入 If...Then 結構。


以下示例可讓您輸入產品的有效期並確定產品是否已過期。

示例:

Sub ExampleIfThenDate

Dim sDate As String

Dim sToday As String

    sDate = InputBox("Enter the expiration date (MM.DD.YYYY)")

    sDate = Right$(sDate, 4) + Mid$(sDate, 4, 2) + Left$(sDate, 2)

    sToday = Date$

    sToday = Right$(sToday, 4)+ Mid$(sToday, 4, 2) + Left$(sToday, 2)

    If sDate < sToday Then

        MsgBox "The expiration date has passed"

    ElseIf sDate > sToday Then

        MsgBox "The expiration date has not yet passed"

    Else

        MsgBox "The expiration date is today"

    End If

End Sub