在VBA中为带有内部引用的UDF设置求解器

时间:2018-08-17 13:47:10

标签: excel vba user-defined-functions solver

我正在尝试创建一个函数,该函数实质上等同于需要在Excel Solver中进行更改以获取求解相等或不相等的变量。由于它经历了可变的迭代次数,因此我不希望记录每个FOR循环输出并使用宏或单元格引用来进行求解。以下是一些示例数据:

Clean_Price =  30,343,540
Number_of_Payments = 4
Coupon = 2.80%
Face = 30,000,000
Zero_Curve = [-0.35%   -0.28%   -0.14%   0.02%] (starting at index 1 for the code)

Function ZS(Clean_Price As Variant, Number_of_Payments As Integer, Coupon As Variant, Face As Variant, AccIn As Variant, Zero_Curve As Range)

    Dim Payment() As Variant                     'Periodic Payments
    ReDim Payment(0 To Number_of_Payments) As Variant

    Dim Disc() As Variant                        'Discount rate
    ReDim Disc(0 To Number_of_Payments) As Variant

    Dim SP As Variant                            'Sumproduct of payments and discount rates

    Dim i As Integer
    For i = 0 To Number_of_Payments

        Select Case i
        Case 0
            Payment(i) = AccIn
            Disc(i) = 1 / (1 + Zero_Curve(i) + ZS) ^ i

        Case Number_of_Payments - 1
            Payment(i) = (AccIn / Coupon) + (Coupon * Face)
            Disc(i) = 1 / (1 + Zero_Curve(i) + ZS) ^ i

        Case Number_of_Payments
            Payment(i) = ((Coupon * Face) - (AccIn)) + (((Coupon * Face) - (AccIn)) / Coupon)
            Disc(i) = 1 / (1 + Zero_Curve(i) + ZS) ^ i

        Case Else
            Payment(i) = Coupon * Face
            Disc(i) = 1 / (1 + Zero_Curve(i) + ZS) ^ i

        End Select
    Next i

    'Solver statements
    SP = Application.WorksheetFunction.SumProduct(Payment(), Disc())
    'ZS such that SP/(Clean_Price+AccIn) = 1

End Function

0 个答案:

没有答案