此VBA函数始终返回0

时间:2019-07-15 09:09:01

标签: excel vba

我正在用Excel编写一个函数,以将佣金率应用于取决于利润率的利润。利润和利润率都是该功能的输入。但是,每当我运行此函数时,尽管输入应返回其他结果,但它始终返回0。

我已经多次查看代码,并检查我的输入是否有效,但是找不到问题。利润率是百分比形式的分数。

我的代码示例如下所示:

    'If Profit Margin is below 20% then no commission
'If Profit Margin is above 20% commission is 5%
'If Profit Margin is above 25% commission is 10%
'If Profit Margin is above 30% commission is 15%
'If Profit Margin is above 40% commission is 25%
'If Profit Margin is above 50% commission is 33%





Function CommissionPicker(ProfitMargin, Profit)


If 0.25 > ProfitMargin >= 0.2 = True Then
   CommissionPicker = 0.05 * Profit

   ElseIf 0.3 > ProfitMargin >= 0.25 = True Then
   CommissionPicker = 0.1 * Profit

   ElseIf 0.4 > ProfitMargin >= 0.3 = True Then
   CommissionPicker = 0.15 * Profit

   ElseIf 0.5 > ProfitMargin >= 0.4 = True Then
   CommissionPicker = 0.25 * Profit

   ElseIf ProfitMargin >= 0.5 = True Then
   CommissionPicker = 0.33 * Profit

   ElseIf ProfitMargin < 0.2 = True Then
   CommissionPicker = 0 * Profit

   Else
   End If


End Function

如果ProfitMargin低于20%,我期望输出为0,0.05 x ProfitMargin的输入利润值在20%和25%之间,0.1 x ProfitMargin的输入利润值在25%和30%之间,0.15 x ProfitMargin的输入利润值在30%到40%之间,0.25 x ProfitMargin的输入利润值在40%和50%之间,以及0.33 x ProfitMargin的输入利润值在50%以上。但是,方程始终返回0。

2 个答案:

答案 0 :(得分:1)

@PEH的答案对于If语句的语法是正确的。但是,我建议您重新组织代码,这将简化逻辑并使其更易于阅读和维护:

Function CommissionPicker(ProfitMargin, Profit)

    If ProfitMargin < 0.2 Then
        CommissionPicker = 0 * Profit
    ElseIf ProfitMargin < 0.25 Then
        CommissionPicker = 0.05 * Profit
    ElseIf ProfitMargin < 0.3 Then
        CommissionPicker = 0.1 * Profit
    ElseIf ProfitMargin < 0.4 Then
        CommissionPicker = 0.15 * Profit
    ElseIf ProfitMargin < 0.5 Then
        CommissionPicker = 0.25 * Profit
    Else
        CommissionPicker = 0.33 * Profit
    End If

End Function

答案 1 :(得分:0)

您不能一次执行多个<>检查。您需要使用And

If ProfitMargin < 0.25 And ProfitMargin >= 0.2 Then

另外,我建议为所有变量指定一种类型:

Function CommissionPicker(ByVal ProfitMargin As Double, ByVal Profit As Double) As Double

说明

为什么If 0.25 > ProfitMargin >= 0.2 = True Then失败?

因为它首先检查0.25 > ProfitMargin的结果是TrueFalse,所以下一个检查将是例如True >= 0.2False >= 0.2True-1,而False0,这是-1 >= 0.20 >= 0.2,两者都是False。那么最后一个检查是False = True,因此If语句是False

替代代码,我推荐类似的

Function CommissionPicker(ByVal ProfitMargin As Double, ByVal Profit As Double) As Double
    Select Case ProfitMargin
        Case Is < 0.2
            CommissionPicker = 0 * Profit
        Case Is < 0.25
            CommissionPicker = 0.05 * Profit
        Case Is < 0.3
            CommissionPicker = 0.1 * Profit
        Case Is < 0.4
            CommissionPicker = 0.15 * Profit
        Case Is < 0.5
            CommissionPicker = 0.25 * Profit
        Case Else
            CommissionPicker = 0.33 * Profit
    End Select
End Function