如何传递和循环,一个不确定的数组在VBA中的函数?
我的function在一定范围内,比如无风险利率,并产生一系列贴现因子。 问题似乎在循环中,有三个方面:
(a)在一个数组上调用一个fn,
(b)指定数组点,
(c)使用循环i作为fn参数。
是围绕每个数组使用循环的最好方法(点i),还是可以通过调用函数来填充整个数组?
Function CreateDiscArray(RFR_array As Range) Dim MyArray() As Variant MyArray = RFR_array Dim xDimRate As Integer xDimRate = UBound(MyArray, 1) Dim TempArray() As Variant For i = 1 To xDimRate Step 1 TempArray(i, 1) = DiscFact(MyArray(i), i) Next i CreateDiscArray() = TempArray() End Function
。
Function DiscFact(Rate, Tenor) If Tenor < 1 Then DiscFact = (1 + Tenor * Rate) If Tenor >= 1 Then DiscFact = (1 + Rate) ^ (-Tenor) End Function
也就是说有可能只是打电话,没有循环:
CreateDiscArray = DiscFact(MyArray(,1), 1 to xDimRate)
您的原始代码有一些问题
-
你没有使用
Option Explicit
,所以你不知道i
没有声明。 -
你不是维度
TempArray
,所以你的代码不能分配给它的索引。 -
你引用了
myArray(i)
,因为有2个维度,所以你必须使用myArray(i,1)
。 -
您正在使用
i
计数器(基于1)作为男高音。 这是一个糟糕的deviseselect,因为你的男高音并不总是一致的长度,你可以期望有很多短期的高音。 此外,这是一个错误,因为i >= 1
将始终为TRUE
所以,为了使你的原始function可行的代码 :
Option Explicit Function CreateDiscArray(RFR_array As Range) Dim MyArray() As Variant MyArray = RFR_array.Value Dim xDimRate As Integer xDimRate = UBound(MyArray, 1) ReDim TempArray(LBound(MyArray) To UBound(MyArray), LBound(MyArray, 2) To UBound(MyArray, 2)) As Variant Dim i As Long For i = 1 To xDimRate Step 1 TempArray(i, 1) = DiscFact(MyArray(i, 1), i) Next i CreateDiscArray = TempArray End Function Function DiscFact(Rate, Tenor) 'BUG: Tenor will always be >= 1 If Tenor < 1 Then DiscFact = (1 + Tenor * Rate) If Tenor >= 1 Then DiscFact = (1 + Rate) ^ (-Tenor) End Function
但这不是你的问题。 正如其他人指出的那样,VBA本身不支持任何东西,但是您使用的是Excel,因此您可以select以下选项:
首先,我们通过在rates
之外增加一系列tenors
来解决男高音的问题。 男高音在A1:A3
,费率在B1:B3
。 我们可以在C1:C3
使用一个数组公式C1:C3
=IF(A1:A3<1,1+A1:A3*B1:B3,(1+B1:B3)^(-A1:A3))
A | B | C --+-----|------|------------------------------------------------- 1 | .5 | 99 | {=IF(A1:A3<1,1+A1:A3*B1:B3,(1+B1:B3)^(-A1:A3))} 2 | 1 | 97 | 3 | 2 | 95 |
而且,如果命名范围名称为Tenor和Rate,则可以将数组公式重新定义为=IF(Tenor<1,1+Tenor*Rate,(1+Rate)^(-Tenor))
如果你真的希望这个解决scheme在VBA中,你需要改变你的函数签名来接受tenor 和 rate范围,然后使用Application.Evaluate
和一个构造的公式来得到一个结果数组。
用一个笨拙的解决scheme,不关心工作表或工作簿:
Public Function DiscFactor(rates As Range, tenors As Range) As Variant Dim Rate As String Dim Tenor As String Rate = rates.Address Tenor = tenors.Address DiscFactor = Application.Evaluate("=IF(" & Tenor & "<1,1+" & Tenor & "*" & Rate & ",(1+" & Rate & ")^(-" & Tenor & "))") End Function