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

在本示例中,若条件 {雇员.部门} = "Sales" 求值为真,则处理

{Employee.Salary} * 0.06

表达式。否则处理 Else 后面的表达式,也就是

{Employee.Salary} * 0.04

表达式。

假设另一公司想要发给其员工 4% 的奖金,但奖金最低金额是 $1,000。注意没有包含 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。现在需要使用一个 Else If 子句。下例只有一个 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;

示例

假设某公司要大概计算出员工需缴纳的税额并写出适当的信息。收入低于八千美元不必纳税,收入介于八千美元和两万美元应缴纳 20%,收入介于两万美元和三万五千美元应缴纳 29%,而收入超过三万五千美元应缴纳 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 变量赋值。满足某个条件时执行多个语句通常很有用。

另请参见

分组表达式