选择案例
当许多不同的条件成为可能时,可以使用 Select Case
。从上到下检查条件,只执行匹配的第一个案例。
Sub TestCase()
Dim MyVar As String
Select Case MyVar 'We Select the Variable MyVar to Work with
Case "Hello" 'Now we simply check the cases we want to check
MsgBox "This Case"
Case "World"
MsgBox "Important"
Case "How"
MsgBox "Stuff"
Case "Are"
MsgBox "I'm running out of ideas"
Case "You?", "Today" 'You can separate several conditions with a comma
MsgBox "Uuuhm..." 'if any is matched it will go into the case
Case Else 'If none of the other cases is hit
MsgBox "All of the other cases failed"
End Select
Dim i As Integer
Select Case i
Case Is > 2 '"Is" can be used instead of the variable in conditions.
MsgBox "i is greater than 2"
'Case 2 < Is '"Is" can only be used at the beginning of the condition.
'Case Else is optional
End Select
End Sub
Select Case
块的逻辑可以反转以支持不同变量的测试,在这种情况下我们也可以使用逻辑运算符:
Dim x As Integer
Dim y As Integer
x = 2
y = 5
Select Case True
Case x > 3
MsgBox "x is greater than 3"
Case y < 2
MsgBox "y is less than 2"
Case x = 1
MsgBox "x is equal to 1"
Case x = 2 Xor y = 3
MsgBox "Go read about ""Xor"""
Case Not y = 5
MsgBox "y is not 5"
Case x = 3 Or x = 10
MsgBox "x = 3 or 10"
Case y < 10 And x < 10
MsgBox "x and y are less than 10"
Case Else
MsgBox "No match found"
End Select
Case 语句也可以使用算术运算符。如果算术运算符用于 Select Case
值,则应在 Is
关键字前面:
Dim x As Integer
x = 5
Select Case x
Case 1
MsgBox "x equals 1"
Case 2, 3, 4
MsgBox "x is 2, 3 or 4"
Case 7 To 10
MsgBox "x is between 7 and 10 (inclusive)"
Case Is < 2
MsgBox "x is less than one"
Case Is >= 7
MsgBox "x is greater than or equal to 7"
Case Else
MsgBox "no match found"
End Select