分支

From Apache OpenOffice Wiki
Jump to: navigation, search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
doc OOo
Book.png

可以使用分支语句限制代码块的执行,直到满足某个特定条件。

If...Then...Else

最常用的分支语句是 If 语句,如以下示例所示:

If A > 3 Then
  B = 2
End If

只有当变量 A 的值大于三时,才会进行 B = 2 赋值。If/Else 子句是 If 语句的变体:

If A > 3 Then
  B = 2
Else
  B = 0
End If

在该示例中,当 A 大于 3 时,则将 2 赋值给变量 B,否则,将 0 赋值给 B

要使用更复杂的语句,您可以级联 If 语句,例如:

If A = 0 Then
  B = 0
ElseIf A < 3 Then
  B = 1
Else 
  B = 2
End If

如果变量 A 的值等于零,则将 0 赋值给 B。如果 A 小于 3(但不等于零),则将 1 赋值给 B。在所有其他情况下(即 A 大于或等于 3),则将 2 赋值给 B

Select...Case

Select...Case 指令可替代级联的 If 语句,它适用于需要根据各种条件来检查某个值的情况:

Select Case DayOfWeek
  Case 1:
    NameOfWeekday = "Sunday"
  Case 2: 
    NameOfWeekday = "Monday"
  Case 3: 
    NameOfWeekday = "Tuesday"
  Case 4:
    NameOfWeekday = "Wednesday"
  Case 5:
    NameOfWeekday = "Thursday"
  Case 6:
    NameOfWeekday = "Friday"
  Case 7:
    NameOfWeekday = "Saturday"
End Select

在该示例中,工作日名称对应于一个数字,因此,对于 Sunday,将 1 赋值给 DayOfWeek 变量;对于 Monday 值,将 2 赋值给该变量,依此类推。

Select 命令并不限于简单的 1:1 赋值,您还可以在 Case 分支中指定比较运算符或表达式列表。以下示例列出了最重要的语法变体:

Select Case Var
  Case 1 To 5                   
    ' ... Var is between the numbers 1 and 5
  Case 6, 7, 8                  
    ' ... Var is 6, 7 or 8
  Case Var > 8 And Var < 11     
    ' ... Var is greater than 8 and less than 11
  Case Else
    ' ... all other instances
End Select
Content on this page is licensed under the Public Documentation License (PDL).


Personal tools