我正在用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%以下,ProfitMargin的投入利润值在20%到25%之间,0.1倍,ProfitMargin的投入利润值在25%到30%之间,ProfitMargin的投入利润值在30%到40%之间,ProfitMargin的投入利润值在40% ~ 50%之间,0.33倍ProfitMargin的投入利润值在50%以上。但是,该方程始终返回值为0。
发布于 2019-07-15 09:12:48
不能同时执行多个<或>检查。您需要使用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,结果是True或False,所以下一个检查将是True >= 0.2或False >= 0.2。True是-1,False是0,这是-1 >= 0.2或0 >= 0.2,两者都是False。最后一次检查是False = True,所以If语句是False。
Alternativley在您的代码中我推荐一些类似的东西
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发布于 2019-07-15 09:20:11
@PEH的答案对于If-statement的语法是正确的。但是,我建议您重新组织代码,这将简化逻辑,并使阅读和维护变得更容易:
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 Functionhttps://stackoverflow.com/questions/57036514
复制相似问题