在 VBA 中使用 Excel Solver 时捕获最大时间/迭代对话框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3984584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catch max time/iteration dialog box when using Excel Solver in VBA
提问by Dan Egan
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, which causes a pop-up dialog box to appear asking whether the user wants to Continue, Stop, or End. In all cases I want it to end, and proceed to the next line of the loop. This will prevent a user from having to sit there and respond each time.
我在 VBA 循环中使用 Excel 2003 中的内置求解器来求解许多不同的问题。有时,求解器会达到最大时间或迭代次数限制,这会导致弹出对话框询问用户是要继续、停止还是结束。在所有情况下,我都希望它结束,然后继续循环的下一行。这将防止用户每次都必须坐在那里做出响应。
It appears someone took a stab at it here, but failed: http://www.excelforum.com/excel-programming/483175-catching-max-iterations-stop-of-solver-in-vba.html
似乎有人在这里尝试了一下,但失败了:http: //www.excelforum.com/excel-programming/483175-cating-max-iterations-stop-of-solver-in-vba.html
回答by chris neilsen
here's a sample solution:
这是一个示例解决方案:
it uses the SolverSolve PassThru method to call a function to handle the solver result at each iteration.
它使用 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