我是VBA的初级用户,我在使用Excel Solver时遇到了一些问题。
基本上我必须计算几种金融工具的公允价值,按起源国家分组。
对于每个国家/地区,解算器将最小化函数以查找模型参数。
到目前为止,我已经能够使其发挥作用,在50个不同的国家/类别中,解决者在49个案例中工作。
这就是我的问题,当谈到这个国家时,解算器在3或4次迭代后逐步退出。使目标函数远离最小化。 但是当我点击一个完全链接到同一子程序的命令按钮时,它会找到一个解决方案。
以下是我的代码的一部分,NSCoeff是与解算器链接的子。
Sub NelsonSiegel()
Dim a, b, c, d, e, f, g, p, s, I, t, v, pv, TIR As Variant
Dim NumBonds, bnd_cnt As Integer
Dim current_wb As String
Dim spot(), df, dfcf, NumberCashFlows, Lambda, Lambda2, Beta1, Beta2, Beta3, Beta4, TimeToCashFlow(), NSPV As Variant
Dim j As Integer
Dim Time() As Variant
Dim A1() As Variant
Dim A2() As Variant
Dim A3() As Variant
Dim A4() As Variant
current_wb = ThisWorkbook.Name
NumBonds = Sheets("bonds").Cells(1, 7).Value
Workbooks(current_wb).Sheets("Nelson_Siegel").Range("n4:s4").Value = 1
NSCoeff
Workbooks(current_wb).Sheets("bonds").Calculate 'download coupon date for NS procedure
Lambda = Worksheets("model").Cells(28, 2)
Beta1 = Worksheets("model").Cells(29, 2)
Beta2 = Worksheets("model").Cells(30, 2)
Beta3 = Worksheets("model").Cells(31, 2)
Beta4 = Worksheets("model").Cells(32, 2)
Lambda2 = Worksheets("model").Cells(33, 2)
这里是NSCoeff sub
Sub NSCoeff()
Dim current_wb As String
current_wb = ThisWorkbook.Name
Workbooks(current_wb).Sheets("Nelson_Siegel").Activate
SolverOk SetCell:="$N$9", MaxMinVal:=2, ValueOf:=0, ByChange:="$N$4:$S$4", _
Engine:=1, EngineDesc:="GRG Nonlinear"
SolverAdd CellRef:="$N$4", Relation:=3, FormulaText:="0.001"
SolverAdd CellRef:="$S$4", Relation:=3, FormulaText:="0.001"
SolverOk SetCell:="$N$9", MaxMinVal:=2, ValueOf:=0, ByChange:="$N$4:$S$4", _
Engine:=1, EngineDesc:="GRG Nonlinear"
SolverOk SetCell:="$N$9", MaxMinVal:=2, ValueOf:=0, ByChange:="$N$4:$S$4", _
Engine:=1, EngineDesc:="GRG Nonlinear"
SolverSolve userFinish:=True
关于如何解决这个问题的任何想法?从另一个子程序启动时,解算器找不到解决方案,但是当它从命令按钮发出时,它可以正常工作。
感谢您的帮助
答案 0 :(得分:1)
第一步是从SolverSolve
捕获返回值。这将允许您确定它结束的原因。
Sub NSCoeff()
Dim current_wb As Workbook
Dim ret As Integer
Set current_wb = ThisWorkbook
current_wb.Sheets("Nelson_Siegel").Activate
SolverOk SetCell:="$N$9", MaxMinVal:=2, ValueOf:=0, ByChange:="$N$4:$S$4", _
Engine:=1, EngineDesc:="GRG Nonlinear"
SolverAdd CellRef:="$N$4", Relation:=3, FormulaText:="0.001"
SolverAdd CellRef:="$S$4", Relation:=3, FormulaText:="0.001"
ret = SolverSolve userFinish:=True
MsgBox "SolverSolve returned a value of " & ret
End Sub
然后你可以咨询Microsoft's Website以确定解算器决定退出的原因。
从那里,您可以使用该信息来确定如何继续。