在VBA中使用Excel Solver时捕获最大时间/迭代对话框

时间:2010-10-21 05:36:40

标签: excel-vba excel-2003 vba excel

我在VBA循环中使用Excel 2003中的内置解算器来解决许多不同的问题。有时,解算器会达到最大时间或迭代限制,这会导致出现一个弹出对话框,询问用户是想要继续,停止还是结束。在所有情况下,我希望它结束​​,并继续循环的下一行。这将防止用户不得不坐在那里并且每次都做出响应。

看来有人在这里捅了一下,但失败了: http://www.excelforum.com/excel-programming/483175-catching-max-iterations-stop-of-solver-in-vba.html

1 个答案:

答案 0 :(得分:2)

这是一个示例解决方案:

它使用SolverSolve PassThru方法调用函数来处理每次迭代时的求解器结果。

Option Explicit

Sub SolverExample()
    Dim results

    ' Set up your solver here...


    ' Execute solve
    SolverOptions StepThru:=True

    results = SolverSolve(True, "SolverIteration")

    Select Case results
    Case 0, 1, 2
        ' solution found, keep final values
        SolverFinish KeepFinal:=1
    Case 4
        'Target does not converge
        'Your code here
    Case 5
        'Solver could not find a feasible solution
        'Your code here
    Case Else
        'Your code
    End Select
End Sub

Function SolverIteration(Reason As Integer)
    ' Called on each solver iteration

    Const SolverContinue As Boolean = False
    Const SolverStop As Boolean = True
    '
    Select Case Reason
    Case 1
        SolverIteration = False ' Continue

    Case 2
        ' Max Time reached
        SolverIteration = True ' Stop

    Case 3
        ' Max Iterations reached
        SolverIteration = True ' Stop

    End Select
End Function