If 陳述式是最有用的控制結構之一。它可在某條件為 True 時,用來驗算一組陳述式;而某條件若為 False,則驗算不同組的陳述式。
注意 當格式化條件式公式時,請一定要使用 Else關鍵字,否則不符合 If 條件的數值可能不會保持原始的格式。若要避免發生這種情況,請使用 DefaultAttribute 函式 (If...Else formula = DefaultAttribute)。
範例
某公司計畫提撥 4% 的紅利給員工,但銷售部門的員工將可得到 6%。下列公式使用 If 陳述式來執行這項任務:
Rem Multi-line If example 1 If {Employee.Dept} = "Sales" Then formula = {Employee.Salary} * 0.06 Else formula = {Employee.Salary} * 0.04 End If
在本範例中,如果條件 {Employee.Dept} = "Sales" 驗算為 True,則會執行
formula = {Employee.Salary} * 0.06
陳述式。否則會處理 Else 之後的陳述式,也就是
formula = {Employee.Salary} * 0.04
。
假定另一家公司要提撥 4% 的紅利 (最少 $1,000) 給員工。請注意範例中並未包含 Else 子句,因為 Else 子句是選擇性的,在此處並不需要。
Rem Multi-line If example 2 formula = {Employee.Salary} * 0.04 If formula < 1000 Then formula = 1000 End If
現在假定前述公司還要將紅利的最高上限訂為 $5,000 元。現在需要使用的是 ElseIf 子句。請注意 ElseIf 只有一個字。以下範例只有一個 ElseIf 子句,可是您可以依需要任意加添。
注意 每個 If 陳述式最多均只能有一個 Else 子句。
如果 If 或 ElseIf 條件均不為 True,Else 子句就會執行。
Rem Multi-line If example 3 formula = {Employee.Salary} * 0.04 If formula < 1000 Then formula = 1000 ElseIf formula > 5000 Then formula = 5000 End If
範例
假設某公司想要計算每位員工稅款的估計值,並顯示適當的訊息。收入如果低於 $8,000 元則不用繳稅,收入在 $8,000 到 $20,000 元之間的需繳納 20% 的稅款,收入在 $20,000 到 $35,000 元之間的需繳納 29% 的稅款,而 $35,000 元以上收入者需繳稅 40% 的稅款。
Rem Multi-line If example 4 Dim tax As Currency, income As Currency income = {Employee.Salary} Dim message As String If income < 8000 Then tax = 0 message = "no" ElseIf income >= 8000 And income < 20000 Then message = "lowest" tax = (income - 8000)*0.20 ElseIf income >= 20000 And income < 35000 Then message = "middle" tax = (20000 - 8000)*0.20 + (income - 20000)*0.29 Else message = "highest" tax = (20000 - 8000)*0.20 + (35000 - 20000)*0.29 + _ (income - 35000)*0.40 End If Dim taxStr As String Rem use 2 decimal places Rem and use the comma as a thousands separator taxStr = CStr (tax, 2, ",") formula = "You are in the " & message & _ " tax bracket. " & _ "Your estimated tax is " & taxStr & "."
請注意,上例中使用變數來簡化計算的邏輯。此外,注意到在某個條件符合時,會執行兩個陳述式:一個指派 tax 變數,另一個指派 message 變數。在符合一個條件時執行多個陳述式條件是很有用的作法。