UDF VBA产生零。没有错误值,只有零。有人可以检查我的代码吗

时间:2018-07-06 10:46:27

标签: vba user-defined-functions

VBA函数是按0.5、1、1.5和2年等计算1年远期利率的。所有结果均为零;没有错误值,只有零。谁能告诉我我要去哪里错了。谢谢

Function OneYearFwdRates(Mty As Range, Spots As Range) As Variant
Dim Maturities()
ReDim Maturities(Mty.Rows.Count)  'Mty is the range of maturities'
Dim SpotRates()
ReDim SpotRates(Spots.Rows.Count)  'Spots is the range of spot rates'
Dim OYFR()                         'OYFR stands for One Year Forward Rates'
ReDim OYFR(Spots.Rows.Count)
Dim i

For i = 2 To Spots.Rows.Count - 2
    OYFR(i) = (1 + SpotRates(i + 2)) ^ (Maturities(i + 2)) _
        / (1 + SpotRates(i)) ^ (Maturities(i)) - 1
Next i
OneYearFwdRates = OYFR

End Function

下面是电子表格。我想用上面的代码填充标题为远期汇率f(x,1)的蓝色列

                        Forward Rate
Maturity    Spot Rate     f(x,1)
 0.00         0.0200    
 0.5          0.0218    
 1.0          0.0231    
 1.5          0.0243    
 2.0          0.0253    
 2.5          0.0261    
 3.0          0.0268    
 3.5          0.0273    
 4.0          0.0277    
 4.5          0.0281    
 5.0          0.0284    
 5.5          0.0287    
 6.0          0.0289    
 6.5          0.0291    
 7.0          0.0293    
 7.5          0.0295    
 8.0          0.0296    
 8.5          0.0298    
 9.0          0.0299    
 9.5          0.0300    
 10.0         0.0301    
 10.5         0.0302    
 11.0         0.0303    
 11.5         0.0303    
 12.0         0.0304    
 12.5         0.0304    

1 个答案:

答案 0 :(得分:1)

问题在于,您永远不会为Maturities()SpotRates分配任何值。只要范围是单行或单列,就不需要这些变量。 SpotRates(1)将返回范围内的第一个单元格,SpotRates(2)将返回第二个单元格。

Function OneYearFwdRates(Mty As Range, Spots As Range) As Double()
    Dim OYFR() As Double                            'OYFR stands for One Year Forward Rates'
    ReDim OYFR(1 To Spots.Rows.Count, 1 To 1)
    Dim i

    For i = 2 To Spots.Rows.Count - 2
        OYFR(i, 1) = (1 + Spots(i + 2)) ^ (Mty(i + 2)) _
                  / (1 + Spots(i)) ^ (Mty(i)) - 1
        ' Debug.Print Spots(i), Mty(i)
    Next i
    OneYearFwdRates = OYFR
End Function

此函数返回一个数组,需要像其他任何数组公式一样使用 Ctrl + Shift + Enter 输入。