Crystal Reports Designer  

If 運算式 (Crystal 語法)

If 運算式是最有用的控制結構之一,它允許您驗算運算式中的條件是否為 True,以及當前者不為 True 時驗算另一個運算式。

注意   當格式化條件式公式時,請一定要使用 Else關鍵字,否則不符合 If 條件的數值可能不會保持原始的格式。若要避免發生這種情況,請使用 DefaultAttribute 函式 (If...Else DefaultAttribute)。

範例

某公司計畫提撥 4% 的紅利給員工,但銷售部門的員工將可得到 6%。以下公式用 If 運算式便可完成:

//If example 1
If {Employee.Dept} = "Sales" Then
   {Employee.Salary} * 0.06
Else
   {Employee.Salary} * 0.04

在本範例中,如果條件 {Employee.Dept} = "Sales" 驗算為 True,則會執行

{Employee.Salary} * 0.06

運算式;否則,執行 Else 之後的運算式,也就是執行

{Employee.Salary} * 0.04

假定另一家公司要提撥 4% 的紅利 (最少 $1,000) 給員工。請注意範例中並未包含 Else 子句,因為 Else 子句是選擇性的,在此處並不需要。

//If example 2
Local CurrencyVar bonus := {Employee.Salary} * 0.04;
If bonus < 1000 Then
   bonus := 1000;
//The final expression is just the variable 'bonus'.
//This returns the value of the variable and is the
//result of the formula
bonus

完成範例 2 的另一個方法是使用 Else 子句:

//If example 3
Local CurrencyVar bonus := {Employee.Salary} * 0.04;
If bonus < 1000 Then
   1000
Else
   bonus

現在假定前述公司還要將紅利的最高上限訂為 $5,000 元。現在需要使用的是 ElseIf 子句。以下範例只有一個 Else If 子句,但是您可以視需要增加。

注意   每個 If 運算式最多均只能有一個 Else 子句。

如果沒有任何 If 或 Else If 條件為 True 時,才會執行 Else 子句。

//If example 4
Local CurrencyVar bonus := {Employee.Salary} * 0.04;
If bonus < 1000 Then
   1000
Else If bonus > 5000 Then
   5000
Else
   bonus;

範例

假設某公司想要計算每位員工稅款的估計值,並顯示適當的訊息。收入如果低於 $8,000 元則不用繳稅,收入在 $8,000 到 $20,000 元之間的需繳納 20% 的稅款,收入在 $20,000 到 $35,000 元之間的需繳納 29% 的稅款,而 $35,000 元以上收入者需繳稅 40% 的稅款。

//If example 5
Local CurrencyVar tax := 0;
Local CurrencyVar income := {Employee.Salary};
Local StringVar message := "";
If income < 8000 Then
(
   message := "no";
   tax := 0
)
Else If income >= 8000 And income < 20000 Then
(
   message := "lowest";
   tax := (income - 8000)*0.20
)
Else If 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
);
//Use 2 decimal places and the comma as a
//thousands separator
Local StringVar taxStr := CStr (tax, 2, ",");
"You are in the " & message & " tax bracket. " &
"Your estimated tax is " & taxStr & "."
注意   使用變數是為了簡化計算的邏輯。此外,任何一個條件符合時都會執行兩個運算式,一個是指派變數 tax,另一個是指派變數 message。如果條件的結果會執行多個運算式,這種用法相當有用。

請參閱

Grouping 運算式