I am trying to solve an optimization problem where one of the input variables must be bounded by a minimum and a maximum constraint. Because I don’t run SolverReset at the end, I can tell afterwards that Solver is ignoring the third constraint ($F$5 <= 1). I can also tell because sometimes it gives me an answer where $F$5 > 1.
When I use Solver manually I’m able to add in the third constraint. I’ve tried recording the macro to see what I’m missing, but I’m still stumped. I’m running Excel 2007. Any ideas? Thanks,
Public Sub SEDMSolver() SolverReset SolverAdd CellRef:="$F$5", Relation:=3, FormulaText:="0.1" SolverAdd CellRef:="$F$4", Relation:=3, FormulaText:="0" SolverAdd CellRef:="$F$5", Relation:=1, FormulaText:="1" SolverOk SetCell:="$G$8", MaxMinVal:=2, ValueOf:="0", ByChange:="$F$4:$F$5" SolverSolve userFinish:=True End Sub
Solver can be a bit fluky. Try setting your MaxMinVal=2 line above the first. When I run solver macros, I always have to set that above the constraints. Occasionally it will throw errors.
I tried to replicate your issue (using excel 2010), but it works for me. With the MxMinVal at the beginning and end. You could try restarting your machine and excel and see if the issue remains. But your code does work for me, all three constraints load.
Another general suggestion I would have for your code is to add:
Application.Calculation = xlAutomatic
This will turn the calculations to automatic. I have had it get turned off while running more complex macros involving solver.
Set some cell (e.g H9) to 1 and use reference to this cell in a code.
SolverAdd CellRef:=”$F$5″, Relation:=1, FormulaText:=”$H$9″
From my experience using solver and trying to automate it with VBA, the best solution is to not automate Excel’s sorver but write your own iteration to solve for your target.
For j = 1 To 100 result = someCalculation If result > minConstraint Then result = j - 1 Exit For Else End If Next j