If...Then...Else 语句

定义一个或多个语句块,仅当给定条件为 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,将执行后面的语句直至遇到 Else 或者 ElseIf 语句。如果条件为 False,并且后面跟有ElseIf 语句,LibreOffice Basic 检测下一个条件,如果为 True 则执行后面的语句。如果条件为 False,程序将继续测试下一个 ElseIf 或者 Else 语句。在 Else 之后的语句,只有在前面所有的条件判断都不为 True 的情况下才会被执行。当测试完所有条件并执行了相应的语句之后,程序将继续执行 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