如何在内置函数中使用IF语句

问题描述

im试图创建一个VBA内置函数,其中根据需要进行一种类型的计算。这是我试图做的,但是没有用。任何人都有这种类型的功能的例子吗?

Public Function FRPV(ratey As Double,ratet0 As Double,maturity As Date,asof As Date,amount As Double,testif As Double)

If testif = 123 Then
    FRPV = ((1 + (ratey / 100) * (maturity - asof) / 360) * amount) / (1 + (ratet0 / 100) * (maturity - asof) / 360)
    
Else
    FRNPV = (((1 + ratey / 200) ^ ((maturity - asof) / 180)) * amount) / (1 + (ratet0 / 100) * (maturity - asof) / 360)
    
End If

End Function

解决方法

错误是您的返回变量为“ FRPV”,并且在“ Else”块中设置了不同的值FRNPV。

并声明返回类型。然后,该函数的用户将对可能返回的内容有所了解。

除此之外,在函数中将testif参数声明为Long,或者如果您只有yes / no选项,则可以声明为Boolean。也许是整数(因为您可能正在查看息票支付的频率,所以1 =年度,2 =半年,4 =季度等)。

针对整数测试双精度数(具有小数位数)的值可能会充满问题。

Public Function FRPV(ratey As Double,ratet0 As Double,maturity As Date,asof As 
        Date,amount As Double,freq As Integer,simple as Boolean) as Double

    If simple Then
        FRPV = ((1 + (ratey / 100) * (maturity - asof) / 360) * amount) / (1 + (ratet0 
               / 100) * (maturity - asof) / 360)
    Else 'Compound
        FRPV = (((1 + ratey / (freq *100)) ^ (freq * (maturity - asof) / 360)) * amount) / (1 + 
              (ratet0 / 100) * (maturity - asof) / 360) 
    End If

End Function