VBA巢狀if語句

2019-10-16 23:12:54

一個IfElseIf語句可以巢狀在另一個IfElseIf語句中。內部的If語句是根據最外層的If語句執行的。這使得VBScript能夠輕鬆處理複雜的條件。

語法

以下是VBScript中巢狀的If語句的語法。

If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n

   If(boolean_expression) Then
      Statement 1
      .....
      .....
      Statement n
   ElseIf (boolean_expression) Then
      Statement 1
      .....
      ....
      Statement n
   Else
      Statement 1
      .....
      ....
      Statement n
   End If
Else
   Statement 1
    .....
    ....
   Statement n
End If

範例

為了演示目的,這裡借助一個函式來判斷一個正數的型別。如下圖中所示 -

參考實現程式碼 -

Private Sub nested_if_demo_Click()
   Dim a As Integer
   a = 12

   If a > 0 Then
      MsgBox ("The Number is a POSITIVE Number")

      If a = 1 Then
         MsgBox ("The Number is Neither Prime NOR Composite")
      ElseIf a = 2 Then
         MsgBox ("The Number is the Only Even Prime Number")
      ElseIf a = 3 Then
         MsgBox ("The Number is the Least Odd Prime Number")
      Else
         MsgBox ("The Number is NOT 0,1,2 or 3")
      End If
   ElseIf a < 0 Then
      MsgBox ("The Number is a NEGATIVE Number")
   Else
      MsgBox ("The Number is ZERO")
   End If
End Sub

執行上面範例程式碼,得到以下結果 -

點選確定按鈕後,如下所示 -