excel 代码问题 不知道错在哪里

一个vba函数 计算发票金额,如发票金额是错的,正确的是手动计算出来的
单元格 =invoiceamount(A9,B9,$A$2:$D$5)
把各个产品用数字1、2、3、4替代,结果就正确了,已经抓狂了,求大神指教啊!??
Function InvoiceAmount(Product, Volume, Table)
'在表中查找价格
Price = WorksheetFunction.VLookup(Product,Table, 2)
'查找折扣量下限
discountvolume =WorksheetFunction.VLookup(Product, Table, 3)
'如果数量达到折扣下限则应用折扣
If Volume > discountvolume Then
'计算含折扣的发票金额
DiscountPct =WorksheetFunction.VLookup(Product, Table, 4)
InvoiceAmount = Price * discountvolume +Price * _
(1 - Discountpct) * (volume -discountvolume)
Else
'计算没有折扣的发票金额
InvoiceAmount = Price * Volume
End If
End Function
对不起,折扣量桔子是100 ,不是80,写错了,应该没有影响才对,麻烦大神看看代码

自定义函数的基本格式你已经懂了,但代码的写法要按vba的格式书写比较好。看了半天终于搞清楚数量与折扣量的关系。

Function invoiceamount(Product, Volume, Table)

For i = 1 To UBound(Table.Value)

    If Product.Formula = Table(i, 1) Then

       If Volume > Table(i, 3) Then

          invoiceamount = Volume * Table(i, 2) - ((Volume - Table(i, 3)) * Table(i, 2) * Table(i, 4))

       Else

          invoiceamount = Volume * Table(i, 2)

       End If

    End If

Next

End Function

追问

您的我能够理解,但想问一下,用我之前贴出的代码,是不能够计算出结果的,但是把产品“苹果”、“梨子“、“芒果”、“桔子”用1、2、3、4数字代替就能够正确,请问原因在哪里啊

追答

函数式的代码不习惯看,写代码尽量不要用这样的方式。
仔细看了下您的宏表函数,后面少了个参数0,您再试试
Function InvoiceAmount(Product, Volume, Table)
'在表中查找价格
Price = WorksheetFunction.VLookup(Product, Table, 2, 0)
'查找折扣量下限
discountvolume = WorksheetFunction.VLookup(Product, Table, 3, 0)
'如果数量达到折扣下限则应用折扣
If Volume > discountvolume Then
'计算含折扣的发票金额
Discountpct = WorksheetFunction.VLookup(Product, Table, 4, 0)
InvoiceAmount = Price * discountvolume + Price * _
(1 - Discountpct) * (Volume - discountvolume)
Else
'计算没有折扣的发票金额
InvoiceAmount = Price * Volume
End If
End Function

温馨提示:答案为网友推荐,仅供参考