-
Notifications
You must be signed in to change notification settings - Fork 1
Using the Enhanced Callback
Michael Waite edited this page Mar 17, 2026
·
3 revisions
Just as with the Solver Add-in, SolverWrapper allows for monitoring the optimization progress through a callback function. However, SolverWrapper improves on this by not only passing the callback trigger reason but also passing the trial number and the parent SolvProblem object for programming convenience. In order to activate the callback, one must set the following before running the SolveIt method:
'pass the name of the user-defined callback function
oProblem.Solver.UserCallbackMacroName = "ShowTrial" 'assumes ShowTrial function resides in ThisWorkbook
'oProblem.Solver.UserCallbackMacroName = ActiveWorkbook.Name & "!" & "ShowTrial" 'if not in ThisWorkbook
oProblem.SolveItThe following illustrates an example callback function. The function must adhere to the following input arguments, and must return a Boolean specifying whether or not to stop Solver.
Function ShowTrial(ByVal reason As Long, ByVal trialNum As Long, oProblem As SolvProblem) As Boolean
Dim i As Long
If trialNum = 1 Then Debug.Print "Solver started on Worksheet: " & oProblem.SolverSheet.Name
Debug.Print "Trial number: " & trialNum
Debug.Print "Objective: " & oProblem.Objective.CellRange.value
For i = 1 To oProblem.DecisionVars.Count
Debug.Print oProblem.DecisionVars.CellRange(i).Address, oProblem.DecisionVars.CellRange(i).value
Next i
Debug.Print "Constraints Satisfied? " & oProblem.Constraints.AreSatisfied
'decide whether to stop solver based on the reason for the event trigger
Select Case reason
Case SlvCallbackReason.slvShowIterations 'new iteration has completed or user hit esc key
stopSolver = False
Case SlvCallbackReason.slvMaxTimeLimit
stopSolver = True 'if set to True then solver is stopped!
Case SlvCallbackReason.slvMaxIterationsLimit
stopSolver = False
Case SlvCallbackReason.slvMaxSubproblemsLimit
stopSolver = False
Case SlvCallbackReason.slvMaxSolutionsLimit
stopSolver = False
End Select
ShowTrial = stopSolver
End FunctionGetting Started
How-to Topics
- Solver Primer
- A Walkthrough Example
- Using the Enhanced Callback
- Using SolverWrapper Events
- ActiveX DLL FAQ
- Using Without Registration
Object Model Overview