Catch max time/iteration dialog box when using Excel Solver in VBA

后端 未结 1 585
情歌与酒
情歌与酒 2020-12-20 02:22

I am using the built-in solver in Excel 2003 within a VBA loop to solver a number of different problems. Occasionally, the solver hits the maximum time or iterations limit,

相关标签:
1条回答
  • 2020-12-20 02:45

    here's a sample solution:

    it uses the SolverSolve PassThru method to call a function to handle the solver result at each iteration.

    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
    
    0 讨论(0)
提交回复
热议问题