'----------------------------------------------------------------------- Sub demo() '----------------------------------------------------------------------- ' Demonstrate how to call Solver from VBA ' Manual Step: ' Loading Solver via |Tools\Add-Ins| makes it available to the Excel worksheet, but not VBA. ' Thus, this macro returns with an error message, "Sub or Function undefined". ' Solution: Open Visual Basic Editor, go to |Tools| References|, Check Solver" box. ' An easy way to find the settings & correct syntax is to activate the Macro Recorder, ' run the process once manually, then modify the codes the Macro Recorder generates ' ' Instructor: Nam Sun Wang '----------------------------------------------------------------------- ' Clear previous junk SolverReset ' Specify the 1st equation f(x)=0 and the location of the variable x. SolverOk SetCell:="$B$6", MaxMinVal:=3, ValueOf:="0", ByChange:="$B$10:$B$12" ' Specify additional constraints, several at a time SolverAdd CellRef:="$B$7:$B$8", Relation:=2, FormulaText:="0" 'meaning "=0" ' Alternatively, specify additoinal constraints, one at a time ' SolverAdd CellRef:="$B$7", Relation:=2, FormulaText:="0" ' SolverAdd CellRef:="$B$8", Relation:=2, FormulaText:="0" ' Optional: Specify the Solver algorithm if the default values do not yield satisfactory answers. ' SolverOptions MaxTime:=100, Iterations:=100, Precision:=0.000001, AssumeLinear _ ' :=False, StepThru:=False, Estimates:=1, Derivatives:=1, SearchOption:=1, _ ' IntTolerance:=5, Scaling:=False, Convergence:=0.0001, AssumeNonNeg:=False SolverSolve userFinish:=True ' "userFinish" keeps the Solver Results dialog box from showing up End Sub