Sub topic 14
Automating Target-Seeking with VBA and Checking It in Python
Assume you know Excel cell references, formulas, and basic financial modeling. You should also understand revenue, costs, profit, and cash flow. This chapter shows how to automate a one-variable target search in VBA and verify the result independently in Python.
Automating Goal Seek with VBA
Suppose a worksheet contains this break-even model:
| Cell | Meaning | Value or formula |
|---|---|---|
| B1 | Units sold | 1000 |
| B2 | Price per unit | 50 |
| B3 | Variable cost per unit | 30 |
| B4 | Fixed costs | 15000 |
| B5 | Operating profit | `=B1*(B2-B3)-B4` |
A forward calculation starts with units sold and calculates profit. Goal Seek works backward. It changes B1 until B5 equals zero.
The VBA GoalSeek method uses the same three parts as the Excel dialog:
Set cell: the formula cell that must reach a target.Goal: the target value.ChangingCell: the input Excel may change.
Sub SolveBreakEven()
Dim ok As Boolean
ok = Range("B5").GoalSeek( _
Goal:=0, _
ChangingCell:=Range("B1"))
If ok Then
MsgBox "Break-even units: " & Format(Range("B1").Value, "0.00")
Else
MsgBox "Goal Seek did not find a solution."
End If
End SubThe Boolean variable ok matters. It records whether Excel reports success. A macro should not assume that the final value is valid merely because Goal Seek changed a cell.
For a safer macro, qualify the worksheet. Otherwise, Range("B5") refers to the active sheet, which may be the wrong sheet.
Sub SolveBreakEvenSafely()
Dim ws As Worksheet
Dim ok As Boolean
Set ws = ThisWorkbook.Worksheets("Model")
ok = ws.Range("B5").GoalSeek( _
Goal:=0, _
ChangingCell:=ws.Range("B1"))
If Not ok Then
MsgBox "No reliable solution was found."
ElseIf Abs(ws.Range("B5").Value) > 0.01 Then
MsgBox "The result does not meet the tolerance."
End If
End SubThe second check tests the residual. A residual is the difference between the calculated result and the target. Here, the target is zero, so the residual is the absolute value of operating profit.
Checking the Answer in Python
An independent check reduces the risk of a broken cell reference, stale formula, or incorrect model assumption. Python can solve the same equation without reading the Excel result.
from scipy.optimize import brentq
def profit(units):
return units * (50 - 30) - 15000
break_even = brentq(profit, 0, 10000)
residual = profit(break_even)
print(f"Break-even units: {break_even:.2f}")
print(f"Residual profit: {residual:.10f}")brentq searches for a root, which is an input value where a function equals zero. The interval from 0 to 10,000 must contain a sign change. In this example, profit is negative at zero units and positive at 10,000 units.
The result should be about 750 units. If Excel and Python disagree, compare the assumptions first. Common causes include different tax treatment, units measured in thousands, an omitted fixed cost, or a formula referring to the wrong period.
Reproducible Automation
Keep assumptions in clearly labeled input cells. Do not overwrite formulas with solved values unless the workflow explicitly requires it. Save the input assumptions, target, changing cell, solver status, and residual in an output area or log.
Use Python as a check, not as proof that the financial model is correct. Both programs can reproduce the same wrong equation. Independent verification is strongest when the check uses a separately written equation and tests business rules such as nonnegative units and whole-unit rounding.
> callout note > Goal Seek solves the spreadsheet equation you give it. It does not know whether the equation represents the business correctly.
Exercise
In the break-even model, what should you check if VBA reports success but Python returns a different number?
Show answer
Compare the input assumptions, formula logic, units, worksheet references, search interval, and residual against the target.