VBA - If-Else 語句



If 語句由布林表示式及一個或多個語句組成。如果條件為 True,則執行 If 條件下的語句。如果條件為 False,則執行 Else 部分下的語句。

語法

以下是 VBScript 中 If Else 語句的語法。

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

流程圖

VBScript if statement

示例

為了演示的目的,讓我們藉助一個函式找出 Excel 中兩個數字中的較大的數字。

Private Sub if_demo_Click()
   Dim x As Integer
   Dim y As Integer
    
   x = 234
   y = 324
    
   If x > y Then
      MsgBox "X is Greater than Y"
   Else
      Msgbox "Y is Greater than X"
   End If
End Sub

執行上述程式碼後,將生成以下結果。

Y is Greater than X
vba_decisions.htm
廣告
© . All rights reserved.