Solver
Solver
Page 1 of 11
http://support.microsoft.com/kb/843304
10/24/2011
Page 2 of 11
Article ID: 843304 - Last Review: October 11, 2006 - Revision: 1.2
SUMMARY
This article describes how to use Microsoft Excel Solver in Microsoft Excel 97 to create Microsoft Visual Basic macros. Microsoft Excel Solver is a Microsoft Excel add-in. Additionally, this article contains information about how to create macros, how to design a macro, and how to work with constraints of a macro. This article also discusses the algorithm and methods that are used by Microsoft Excel Solver. The following list gives all the topics discussed in the article. Description of the Microsoft Excel Solver How to use the Microsoft Excel Solver functions in a VBA macro How to design a VBA macro that creates and solves a simple Microsoft Excel Solver model How to generate reports for solutions How to use the Microsoft Excel Solver functions in a looping macro How to work with constraints How to change and delete constraints How to load and save your models How to find more information about Microsoft Excel Solver How to learn more about the algorithm and methods that are used by Microsoft Excel Solver
INTRODUCTION
Note You can also use the macros and the examples that are described in this article in Microsoft Excel versions 5.0 and 7.0.
To reference the Microsoft Excel Solver add-in for macros in your workbook, use the following steps:
http://support.microsoft.com/kb/843304
10/24/2011
Page 3 of 11
1. Open your workbook. 2. On the Tools menu, point to Macro, and then click Visual Basic Editor. 3. On the Tools menu, click References. 4. In the Available References list, click to select the Solver.xls check box, and then click OK. Note If you do not see Solver.xls in the Available References list, click Browse. In the Add Reference dialog box, locate and select the Solver.xla file, and then click Open. The Solver.xla file is typically found in the C:\Program Files\Microsoft Office\Office\Library\Solver subfolder. You are now ready to use the Microsoft Excel Solver functions in a VBA macro.
How to design a VBA macro that creates and solves a simple Microsoft Excel Solver model
Although Microsoft Excel Solver offers many functions, the following three functions are fundamental to creating and to solving a model: The SolverOK function The SolverSolve function The SolverFinish function
http://support.microsoft.com/kb/843304
10/24/2011
Page 4 of 11
ShowRef identifies the macro that is called when Microsoft Excel Solver returns an intermediate solution. The ShowRef argument should be used only when TRUE is passed to the StepThru argument of the SolverOptions function.
This article describes how to create a simple Microsoft Excel Solver model interactively. The first step is to create your worksheet for the model. The worksheet will contain some data cells and at least one cell that contains a formula. This formula depends on the other cells in the worksheet. After you set up your worksheet, click Solver on the Tools menu. In the Solver Parameters dialog box, specify the target cell, the value that you are solving for, the range of cells that will be changed, and the constraints. Click Solve to start the solution process. After Microsoft Excel Solver has found a solution, the results appear in your worksheet, and the Microsoft Excel Solver displays a message box that prompts you if you want to keep the final results or if you want to discard them. When you click one of these options, Microsoft Excel Solver finishes. Figure 3 illustrates a simple model that you can create by using these steps. Figure 3. A simple model: The Square Root model
In this example, change cell A1, which contains the formula, =A1^2, to a value that will make cell A2 equal to a value of 50. In other words, find the square root of 50. There are no constraints in the Square Root model. The Find_Square_Root macro accomplishes the following tasks: It sets up a model that will solve the value of cell A2 for a value of 50 by changing the value of cell A1. It solves the model. It saves the final results to the worksheet without displaying the Solver Results dialog box.
http://support.microsoft.com/kb/843304
10/24/2011
Page 5 of 11
This simple macro creates a Microsoft Excel Solver model and solves it without any user intervention. The following code describes the Find_Square_Root macro: SubFind_Square_Root()'Setuptheparametersforthemodel.'SetthetargetcellA2toavalue of50bychangingcellA1.SolverOKSetCell:=Range("A2"),MaxMinVal:=3,ValueOf:=50,_ ByChange:=Range("A1")'SolvethemodelbutdonotdisplaytheSolverResultsdialogbox. SolverSolveUserFinish:=True'Finishandkeepthefinalresults.SolverFinishKeepFinal:=1End Sub
The Find_Square_Root2 macro, is a modified version of the Find_Square_Root macro. If you use the InputBox function, the Find_Square_Root2 macro prompts you for the value that you want to solve for the target cell. After you input a value, the Find_Square_Root2 macro sets this parameter as the value of the SolverOKvalueof argument, solves the problem, saves the results in the variable square root, and then discards the solution and restores the value in the worksheet to its original state. Basically, the Find_Square_Root2 macro illustrates how you can save the results in one or more variables and then restore the changing cells to their original value. The following code describes the Find_Square_Root2 macro: SubFind_Square_Root2()DimvalDimsqroot'Requestthevalueforwhichyouwanttoobtainthe squareroot.val=Application.InputBox(_prompt:="Pleaseenterthevalueforwhichyouwant"& _"tofindthesquareroot:",Type:=1)'Setuptheparametersforthemodel.SolverOK SetCell:=Range("A2"),MaxMinVal:=3,ValueOf:=val,_ByChange:=Range("A1")'Donotdisplaythe SolverResultsdialogbox.SolverSolveUserFinish:=True'SavethevalueofcellA1(thechanging cell)beforeyoudiscard'theresults.sqroot=Range("a1")'Finishanddiscardtheresults. SolverFinishKeepFinal:=2'Showtheresultinamessagebox.MsgBox"Thesquarerootof"&val& "is"&Format(sqroot,"0.00")EndSub
To generate multiple reports, modify the SolverFinish function so that it looks similar to the following sample code: SolverFinishKeepFinal:=2,ReportArray:=Array(1,2)
http://support.microsoft.com/kb/843304
10/24/2011
Page 6 of 11
The Create_Square_Root_Table macro generates the table illustrated in Figure 4. Figure 4. Output that is generated by the Create_Square_Root_Table macro
For example, if a company manufactures TVs, stereos, and speakers, and it uses a common parts inventory of power supplies, speaker cones, and so on. The parts are in limited supply. Your goal is to determine the most profitable mix of products to build. Your profit per unit decreases with volume because additional price incentives are required to load the distribution channel. The diminishing returns exponent is 0.9. This exponent is used to calculate the profit by product in the range G11:I11. Your objective is to find the maximum profit (cell G14). The values that you will change to find the maximum profit are the number of units that you build. The range G9:G11 represents the changing cells in this model. Your only constraint is that the number of parts you use cannot exceed the number of parts you have on hand. With Microsoft Excel Solver, this constraint appears as E3:E7<=B3:B7. If you were to build this Microsoft Excel Solver model interactively, the Microsoft Excel Solver parameters would look similar to those that are in Figure 6. Figure 6. Microsoft Excel Solver parameters for the product mix with Diminishing Profit Margin model
http://support.microsoft.com/kb/843304
10/24/2011
Page 7 of 11
To create and solve the Product Mix with Diminishing Profit Margin model, you will use a new function, the SolverAdd function, in addition to the Microsoft Excel Solver VBA functions that were described earlier. The SolverAdd function adds the constraint to the model. Executing the SolverAdd function is equivalent to clicking the Add button in the Solver Parameters dialog box. The SolverAdd function has the following syntax: SolverAdd (CellRef, Relation, FormulaText) The following information describes the syntax for the SolverAdd function: CellRef references one or more cells that form the left side of the constraint. Relation is the arithmetic relationship between the left and the right sides of a constraint. Relation can be a value between 1 and 5 as in the following example: The value 1 is less than or equal to (<=). The vaue 2 is equal to (=). The value 3 is greater than or equal to (>=). The value 4 is an integer. The value 5 is the binary (a value of zero or one). FormulaText references one or more cells that form the right side of the constraint.** **When you specify a range of cells for the FormulaText argument of the SolverAdd function, note whether the reference is relative or absolute. Generally, you must specify an absolute reference for the FormulaText argument. However, if you do specify relative references for the FormulaText argument, realize that the reference will be relative to the target cell and not the active cell. Note In Microsoft Excel, versions 5.0 and 7.0, use the R1C1 notation when you specify a cell or a range of cells with the FormulaText argument. In contrast, in Microsoft Excel 97, use the A1-style notation to specify the FormulaText argument. Figure 7. Fields that are associated with the SolverAdd arguments
The Maximum_Profit macro that generates a model for the Product Mix with Diminishing Returns model. This macro executes the following functions or arguments:
The SolverOK function sets up the target cell for a maximum value and specifies the cells to change. The SolverAdd function adds the constraint to the model. The SolverSolve function finds a solution without displaying the Solver Results dialog box. The SolverFinish function returns the final results to the worksheet. The following code describes the for Maximum_Profit macro: SubMaximum_Profit()'Setuptheparametersforthemodel.'Determinethemaximumvalueforthe sumofprofitsincellG14'bychangingthenumberofunitstobuildincellsG9:I9.Solverok setcell:=Range("G14"),maxminval:=1,_bychange:=Range("G9:I9")'Addtheconstraintforthe model.Theonlyconstraintisthatthe'numberofpartsuseddoesnotexceedthepartsonhand
http://support.microsoft.com/kb/843304
10/24/2011
Page 8 of 11
Note In Microsoft Excel, versions 5.0 and 7.0, use the R1C1 notation when you specify a cell or range of cells with the FormulaText argument. In contrast, in Microsoft Excel 97, use the A1-style notation to specify the FormulaText argument. When you run the Maximum_Profit macro, Microsoft Excel Solver will find a solution of building 160 TV sets, 200 stereos, and 80 speakers for a maximum profit of $14,917 dollars.
Because constraints are identified by the CellRef and Relation arguments, you can only change the FormulaText argument for the constraint by using the SolverChange function. If the CellRef and the Relation values do not match an existing constraint, you must delete the constraint and then add the modified constraint. To delete a constraint, use the SolverDelete function. The following is the syntax for the SolverDelete function: SolverDelete (CellRef, Relation, FormulaText) Note that the arguments for the SolverDelete function are the same to those you use with the SolverAdd and the SolverChange functions. The following macro illustrates how to delete and add a constraint. In this example, the Change_Constraint_and_Solve2 macro removes the constraint E3:E7<=B3:B7 from the Product Mix with Diminishing Returns model and adds a new constraint. The new constraint is just a modification of the original constraint, where the left and right sides of the constraint are reversed. The following code describes the Change_Constraint_and_Solve2 macro: SubChange_Constraint_and_Solve2()'Reversetheleftandrightsidesoftheconstraint...' DeletetheconstraintE3:E7<=B3:B7andaddthe'constraintB3:B7>=E3:E7.SolverDelete CellRef:=Range("E3:E7"),Relation:=1,_FormulaText:="$B$3:$B$7"SolverAddCellRef:=Range ("B3:B7"),Relation:=3,_FormulaText:="$E$3:$E$7"'ReturntheresultsanddisplaytheSolver Resultsdialogbox.SolverSolveUserFinish:=FalseEndSub
Note In Microsoft Excel, versions 5.0 and 7.0, use the R1C1 notation when you specify a cell or range of cells with the FormulaText argument. In contrast, in Microsoft Excel 97, use the A1-style notation to specify the FormulaText argument.
http://support.microsoft.com/kb/843304
10/24/2011
Page 9 of 11
the Solver Parameter and the Solver Options dialog boxes. Because only the last problem is saved with the worksheet, you will lose all other problems unless you explicitly save them. To save them, click Save Model in the Solver Options dialog box. Similarly, when you want to restore the previously saved parameters, click Load Model in the Solver Options dialog box. Solver models are stored in a range of cells on a worksheet. The first cell in the range contains the formula for the target cell. The second cell in the range contains the formula that identifies the changing cells in the model. The last cell in the range contains an array that represents the options set in the Solver Options dialog box. The cells between the second cell and the last cell contain the formulas that represent the constraints in the model. Figure 8 illustrates a model for employee scheduling. Assume that you work for a small manufacturer. This table shows each employees hourly rate of pay, the number of hours they are scheduled, and a projected number of units each employee can produce in one hour. Your goal is to meet a specific quota for the number of units produced while minimizing the cost of labor. Figure 8. Employee Scheduling mode l
Two additional factors (or constraints) that you must consider are the minimum/maximum number of hours any one employee can work and the number of units that you intend to produce. If for a specified week, you need to produce 3975 units and you want each employee to work between 30 and 45 hours, the Microsoft Excel Solver parameters would look similar to those outlined in the following table: Parameter Target cell Cell Range $D$12 Description Cost of labor. Hours worked per employee.
$C$2:$C$8 <= 45 Maximum hours per employee is 45. $C$2:$C$8 >= 30 Minimum hours per employee is 35. $G$12 = 3975 Number of units is 3975.
Your goals are to solve for optimal labor cost on a weekly basis, to save each model weekly, and to be able to load any weekly model when you need it. In a macro, the Microsoft Excel Solver parameters for a model can be saved and loaded by using the SolverSave and the SolverLoad functions respectively. The SolverSave and the SolverLoad functions have the following syntax: SolverSave (SaveArea) SolverLoad (LoadArea) The SolverSave and the SolverLoad functions each have only one argument, SaveArea and the LoadArea arguments respectively. These arguments specify a range on a worksheet where the model information is stored. The following New_Employee_Schedule macro, demonstrates how to create, to solve, and to save a model based on user input. The user is asked to supply the date of the model, the number of units to produce, and the minimum and maximum number of hours per employee. These data is then used to create the model. The model is solved and then saved with the user input. The following code describes the New_Employee_Schedule macro:
http://support.microsoft.com/kb/843304
10/24/2011
Page 10 of 11
SubNew_Employee_Schedule()'Prompttheuserforthedateofthemodel,theunitstoproduce,' andthemaximumandminimumnumberofhoursperemployee.ModelDate=Application.InputBox(_ Prompt:="DateofModel:",Type:=2)Units=Application.InputBox(_Prompt:="ProjectedNumberof Units:",Type:=1)MaxHrs=Application.InputBox(_Prompt:="MaximumNumberofHoursPer Employee:",Type:=1)MinHrs=Application.InputBox(_Prompt:="MinimumNumberofHoursPer Employee:",Type:=1)'ClearanypreviousSolversettings.SolverReset'Setthetargetcell,D12, toaminimumvaluebychanging'therange,C2:C8.SolverOkSetCell:=Range("$D$12"),MaxMinVal:=2, _ByChange:=Range("C2:C8")'Addtheconstraintthatnumberofhoursworked<=MaxHrs.SolverAdd CellRef:=Range("C2:C8"),Relation:=1,FormulaText:=MaxHrs'Addtheconstraintthatnumberof hoursworked>=MinHrs.SolverAddCellRef:=Range("C2:C8"),Relation:=3,FormulaText:=MinHrs'Add theconstraintthatnumberofunitsproduced=Units.SolverAddCellRef:=Range("G12"), Relation:=2,FormulaText:=Units'Solvethemodelandkeepthefinalresults.SolverSolve UserFinish:=TrueSolverFinishKeepFinal:=1'SavetheinputvaluesforModelDate,MaxHrs,MinHrs, andUnits'incolumnsI:L.SetModelRange=Range("I2:R2").CurrentRegion.Offset(_Range ("I2:R2").CurrentRegion.Rows.Count).Resize(1,1)ModelRange.Resize(1,4)=Array("'"&Format (ModelDate,"m/d/yy"),_Units,MaxHrs,MinHrs)'SavethemodelparameterstotherangeM:Rin theworksheet.SolverSaveSaveArea:=ModelRange.Offset(,4).Resize(1,6)EndSub
Note In Microsoft Excel, versions 5.0 and 7.0, use the R1C1 notation when you specify a cell or range of cells with the FormulaText argument. In contrast, in Microsoft Excel 97, use the A1-style notation to specify the FormulaText argument. Figure 9 illustrates how the saved model information appears on the worksheet. Figure 9. Model information that is saved by the New_Employee_Schedule macro
The New_Employee_Schedule macro saves each new model to the worksheet. The Load_Employee_Schedule macro can load one of these saved models. The macro prompts the user for the model to load and then searches column I for the model date. If the model date is found, the Load_Employee_Schedule macro loads the corresponding model, solves it, and then keeps the final results. The following code describes the New_Employee_Schedulemacro: SubLoad_Employee_Schedule()'Promptforthedateofthemodel.ModelDate=Application.InputBox (_Prompt:="DateofModeltoLoad:",Type:=2)'LocatethedateincolumnI.SetDateRange= Range("I2").CurrentRegion.Resize(,1)r=Application.Match(ModelDate,DateRange,0)IfIsError(r) Then'DisplayamessageifthemodeldateisnotfoundMsgBox"Cannotfindamodelwiththedate "&ModelDateElse'Ifthemodeldateisfound,loadthemodelintoSolver,'solvethemodel, andkeepthefinalresults.SolverLoadLoadArea:=DateRange.Offset(r1,4).Resize(1,6) SolverSolveUserFinish:=TrueSolverFinishKeepFinal:=1EndIfEndSub
The New_Employee_Schedule macro introduces the SolverReset function. The SolverReset function can be used to delete all cell selections and constraints in the Solver Parameters dialog box and to reset all settings in The SolverReset function has no arguments.
For help with specific solver messages, see Frontline Systems (http://www.frontsys.com/solvmsgs.htm) . For hints on building readable, manageable models, see Frontline Systems (http://www.frontsys.com/solvmsgs.htm) . For additional information about the Solver limits for constraints and, click the following article number to view the article in the Microsoft Knowledge Base: 75714 (http://support.microsoft.com/kb/75714/ ) Solver limits for constraints For several examples that use the Microsoft Excel Solver add-in in Microsoft Excel, see the Solvsamp.xls sample file.
http://support.microsoft.com/kb/843304
10/24/2011
Page 11 of 11
The following is the default location of the sample file that is included with Microsoft Excel 97: \Program Files\Microsoft Office\Office\Examples\Solver\SolvSamp.xls The following is the default location of the sample file that is included with Microsoft Excel 7.0: \MSOffice\Excel\Examples\Solver\SolvSamp.xls The following is the default location of the sample file that is included with Microsoft Excel 5.0: \Excel\Examples\Solver\SolvSamp.xls
How to learn more about the algorithm and methods that are used by Microsoft Excel Solver
Microsoft Excel Solver uses the Generalized Reduced Gradient (GRG2) nonlinear optimization code that was developed by Leon Lasdon, University of Texas at Austin, and Allan Waren, Cleveland State University. For additional information about the algorithm used by Microsoft Excel Solver, click the following article number to view the article in the Microsoft Knowledge Base: 82890 (http://support.microsoft.com/kb/82890/ ) Solver uses generalized reduced
Linear and integer problems use the simplex method with bounds on the variables, and the branch-and-bound method, implemented by John Watson and Dan Fylstra, Frontline Systems, Inc. For more information about the internal solution process used by Solver, contact:
FrontlineSystems,Inc.P.O.Box4288InclineVillage,NV894504288(702)8310300Website: http://www.frontsys.comElectronicmail:info@frontsys.com
Selections of the Microsoft Excel Solver program code are copyright 1990, 1991, 1992, and 1995 by Frontline Systems, Inc. Portions are copyright 1989 by Optimal Methods, Inc. Note The Microsoft Excel Solver add-in that is discussed in this article is provided "as is" and we do not guarantee that it can be used in all situations. Although Microsoft Support Professionals can help with the installation and existing functionality of this add-in, they will not modify the add-in to provide new functionality. NO WARRANTY. The software is provided "as-is," without warranty of any kind, and any use of this software product is at your own risk.
APPLIES TO
Keywords: kbhowto kbmacroexample kberrmsg kbaddin kbvba kbprogramming kbinfo KB843304
Retired KB Content Disclaimer This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
http://support.microsoft.com/kb/843304
10/24/2011