Sub topic 14
Automating target-seeking with VBA and checking it in Python
This chapter assumes you can run Goal Seek and Solver from the ribbon, and that you can read and record a basic VBA macro. You also need to know the break-even model and the product-mix model from earlier chapters. Here you will turn those manual steps into repeatable macros and check the results with an independent calculation.
Why automate, and what automation adds
Running Goal Seek by hand works once. Automation matters when you run the same search many times: every month with new actuals, for each scenario, or for each product line. A macro gives you three things the dialog does not:
- The same steps run in the same order each time.
- A return value or status code that your code can test.
- A place to restore the inputs and record what happened.
The risk is that a macro hides failures. If it runs quietly and leaves an unsolved model behind, nobody sees the problem. Every macro in this chapter therefore tests its own result.
Automating Goal Seek
Range.GoalSeek takes the same three arguments as the dialog. The range you call it on is the set cell. Goal is the target value, and ChangingCell is the input to adjust. It returns True if the search succeeded and False otherwise.
Use the break-even layout from earlier: units in B1, price in B2, variable cost in B3, fixed costs in B4, and operating profit in B5 as =B1*(B2-B3)-B4. Rename the sheet Model.
Option Explicit
Sub SolveBreakEven()
Dim ws As Worksheet
Dim startValue As Double
Dim ok As Boolean
Set ws = ThisWorkbook.Worksheets("Model")
startValue = ws.Range("B1").Value
ok = ws.Range("B5").GoalSeek(Goal:=0, ChangingCell:=ws.Range("B1"))
If (Not ok) Or Abs(ws.Range("B5").Value) > 0.01 Then
ws.Range("B1").Value = startValue
MsgBox "Goal Seek did not reach the target. Inputs restored.", vbExclamation
Else
ws.Range("D1").Value = ws.Range("B1").Value
End If
End SubThe macro does four things that matter:
- It saves the starting value of
B1before the search. - It checks the return value.
- It also checks the residual, meaning how far
B5is from the goal. ATrueresult only means the search stopped within its tolerance, so your own check should reflect what the business accepts. - It restores the input on failure, so the model is never left in a half-solved state.
Controlling tolerance
Goal Seek uses the workbook's iteration settings. Application.MaxChange is the tolerance, which defaults to 0.001. Application.MaxIterations is the cap on steps, which defaults to 100. These are application-wide settings that stay changed after your macro ends, so save and restore them:
Sub SolveWithTightTolerance()
Dim oldChange As Double
Dim oldIter As Long
Dim ok As Boolean
oldChange = Application.MaxChange
oldIter = Application.MaxIterations
Application.MaxChange = 0.000001
Application.MaxIterations = 500
ok = Worksheets("Model").Range("B5").GoalSeek( _
Goal:=0, ChangingCell:=Worksheets("Model").Range("B1"))
Application.MaxChange = oldChange
Application.MaxIterations = oldIter
If Not ok Then MsgBox "No solution found."
End SubRestore the settings before any code path that exits early. If the macro stops on an error with a tight tolerance still set, other workbooks you open will inherit it.
Automating Solver
Solver is driven through functions from the Solver add-in. Before the code compiles, do two things:
- Enable the Solver add-in in Excel (File > Options > Add-ins).
- In the VBA editor, choose Tools > References and tick Solver.
Without the reference, calls such as SolverOk fail with "Sub or Function not defined".
Take the product-mix model with B1 for units of x and B2 for units of y. Profit in B3 is =20*B1+30*B2. Machine hours in B4 are =2*B1+4*B2. Total units in B5 are =B1+B2.
Option Explicit
Sub SolveProductMix()
Dim result As Long
SolverReset
SolverOk SetCell:="$B$3", MaxMinVal:=1, ByChange:="$B$1:$B$2", Engine:=2
SolverAdd CellRef:="$B$4", Relation:=1, FormulaText:="100"
SolverAdd CellRef:="$B$5", Relation:=1, FormulaText:="40"
SolverAdd CellRef:="$B$1:$B$2", Relation:=3, FormulaText:="0"
result = SolverSolve(UserFinish:=True)
Select Case result
Case 0, 1, 2
SolverFinish KeepFinal:=1
Case Else
SolverFinish KeepFinal:=2
MsgBox "Solver stopped with code " & result & ". Original values restored.", vbExclamation
End Select
End SubThe codes the macro depends on:
| Argument | Value | Meaning |
|---|---|---|
| `MaxMinVal` | 1, 2, 3 | Maximize, minimize, or match a target value |
| `Engine` | 1, 2, 3 | GRG Nonlinear, Simplex LP, Evolutionary |
| `Relation` | 1, 2, 3 | Less than or equal, equal, greater than or equal |
| `Relation` | 4, 5 | Integer, binary |
SolverSolve returns a status code. Codes 0, 1, and 2 mean Solver found a solution, converged, or could not improve further. Other codes cover cases such as an infeasible problem, an objective that does not converge, or a linearity check that fails under Simplex LP. Look up the full list in the Solver documentation and map the ones you expect to a clear message.
SolverFinish KeepFinal:=1 keeps the solution in the sheet. KeepFinal:=2 restores the original values. UserFinish:=True skips the results dialog so a batch run does not wait for a click.
Call SolverReset first. Otherwise constraints from a previous run, or from the sheet's saved Solver model, can combine with the ones you add and produce confusing results.
A workflow that includes verification
The Python step is a cross-check. If a spreadsheet-based search and an independent solver agree, you have good evidence that the answer reflects the math and not an accident of the sheet.
Checking in Python
Re-implement only the model's economics, not the spreadsheet layout. For break-even, a bracketing root finder gives the answer to machine precision:
from scipy.optimize import brentq
def profit(units):
return units * (50 - 30) - 15000
break_even = brentq(profit, 0, 10000)
print(round(break_even, 2))This prints 750.0. To compare against a value exported from Excel, wrap the check in a function with an explicit tolerance:
from scipy.optimize import brentq
def profit(units, price=50.0, var_cost=30.0, fixed=15000.0):
return units * (price - var_cost) - fixed
def check_break_even(excel_value, tol=0.01):
expected = brentq(profit, 0, 10000)
gap = abs(excel_value - expected)
return gap <= tol, expected, gap
ok, expected, gap = check_break_even(750.0004)
print(ok, round(expected, 4), round(gap, 4))A gap of 0.0004 units passes a 0.01 tolerance. A gap of several units would indicate that Goal Seek stopped early or that the sheet's formulas differ from your Python model, and either case needs investigating.
The same idea works for Solver. linprog minimizes, so negate the objective to maximize:
from scipy.optimize import linprog
# Maximize 20*x + 30*y, so minimize the negative.
c = [-20, -30]
A_ub = [[2, 4], # machine hours per unit of each product
[1, 1]] # total units limited by a demand cap
b_ub = [100, 40]
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=[(0, None), (0, None)])
print(res.x, -res.fun)The optimum is 30 units of x and 10 units of y, for a profit of 900. If the macro reports different values, compare the constraint rows in the sheet with the matrices here. A sign error or a wrong cell reference in the sheet is the usual cause.
Limits of the cross-check
- Agreement shows that the two models match, not that either matches reality. If both encode the same wrong assumption, they will agree.
- Linear programs have one optimal objective value, but there can be several variable combinations that reach it. Compare the objective value first, then the variables.
- Nonlinear problems can have several local optima. Python may land in a different one from GRG Nonlinear. A different answer is a reason to test several starting points, not proof that one tool is wrong.
- Keep the Python model small. A large re-implementation becomes a second model to maintain and debug.
Practical habits
- Keep all inputs on one sheet and refer to them by name in macros, so a moved row does not silently change what the macro solves.
- Log each run: timestamp, inputs, status code, and residual. A short log table beats memory when a number is challenged later.
- Run the macro from a known starting point. Goal Seek and GRG Nonlinear depend on the starting value, so a stored default input gives repeatable results.
- Store the Python check beside the workbook and re-run it whenever the model structure changes, not only when its numbers change.
Exercise
A macro calls Range("B5").GoalSeek(Goal:=0, ChangingCell:=Range("B1")) and the return value is True. Why should the macro still compare B5 to zero, and what should it do if the gap is too large?
Show answer
True only means the search stopped within the workbook's tolerance (Application.MaxChange, default 0.001) or within its iteration limit, which may not match what the business accepts. The macro should read B5, compare Abs(B5 - Goal) with an explicit tolerance, and if the gap is too large, restore the saved starting value of B1 and report the failure instead of leaving the unsolved model in place.
Exercise
Your Solver macro returns a status code of 0 and keeps the solution of 28 units of x and 12 units of y, with profit 840. The Python linprog check gives 30 and 10 with profit 900. What do you check first?
Show answer
Compare the model definitions. Check that the constraint cells, signs, and right-hand sides in the sheet (100 machine hours, 40 units, non-negativity) match the matrices in Python. Then check that the macro called SolverReset so no old constraint remained, and that the engine is Simplex LP so the answer is a true linear optimum. Since 900 is higher than 840 under the same constraints, the sheet solution is not optimal, so the sheet has an extra or wrong constraint.