[英]This VBA function always returns an answer of 0
我正在用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輸入的利潤值對於30%到40%之間的ProfitMargin,0.25倍於40%和50%之間的ProfitMargin輸入利潤值,以及0.33 x高於50%的ProfitMargin輸入利潤。 但是,等式始終返回值0。
@正常皮膚的答案是對的語法正確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
您不能一次執行多個<
或>
檢查。 您需要使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.