Sub topic 10
The copy-paste macro alternative
This chapter assumes you have read the earlier chapters on average-balance interest, iterative calculation and the circuit-breaker switch. You should be comfortable with named ranges, the cash sweep formulas (Interest, Repayment, Debt_Close) and basic VBA: running a macro, opening the editor with Alt+F11, and reading a For loop.
The idea in one paragraph
Iterative calculation lets Excel loop around a circular reference by itself. The macro approach does the same loop by hand. You keep a live formula that calculates the interest you want, but the rest of the model reads interest from a separate cell that holds a pasted value. A macro copies the live result into the pasted cell, recalculates, and repeats until the two agree. Excel never sees a closed loop, so you can leave iterative calculation switched off.
Where the loop is cut
In the circular version, interest feeds repayment, repayment feeds the closing balance, and the closing balance feeds interest. The macro design adds one cell, Interest_Paste, and moves the break to that cell:
Interest_Calc: =Rate*AVERAGE(Debt_Open, Debt_Close) (live formula, feeds nothing)
Interest_Paste: (a typed or pasted number, not a formula)
Repayment: =MIN(Debt_Open, MAX(0, CFADS - Interest_Paste))
Debt_Close: =Debt_Open - Repayment
Interest_Check: =Interest_Calc - Interest_Paste (should be about 0)Follow the dependencies. Interest_Paste feeds Repayment, which feeds Debt_Close, which feeds Interest_Calc. Nothing reads Interest_Calc except the check cell, so the chain ends there. The model has no circular reference, and Excel's circular warning never appears.
The cost is that Interest_Paste is only as good as the last time someone ran the macro. If CFADS changes and nobody reruns the macro, the model keeps using the old interest figure.
What the macro does
Each pass does three things:
- Recalculate, so
Interest_Calcreflects the currentInterest_Paste. - Compare
Interest_CalcwithInterest_Paste. If the largest difference is below a tolerance, stop. - Otherwise, copy the values of
Interest_CalcintoInterest_Pasteand go round again.
This is the same fixed-point iteration as the Python function earlier in the tutorial. The only difference is that the "previous interest" is stored in a worksheet cell instead of a variable.
A working macro
The macro below assumes two named ranges of the same shape, Interest_Calc and Interest_Paste. They can be a single cell or a row covering every period. Put the code in a standard module.
Option Explicit
Private Const MAX_PASSES As Long = 100
Private Const TOLERANCE As Double = 0.000001
Public Sub SolveInterest()
Dim calcRng As Range
Dim pasteRng As Range
Dim previousMode As XlCalculation
Dim pass As Long
Dim converged As Boolean
Set calcRng = ThisWorkbook.Names("Interest_Calc").RefersToRange
Set pasteRng = ThisWorkbook.Names("Interest_Paste").RefersToRange
previousMode = Application.Calculation
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
On Error GoTo CleanUp
For pass = 1 To MAX_PASSES
Application.Calculate
If MaxAbsDiff(calcRng, pasteRng) < TOLERANCE Then
converged = True
Exit For
End If
pasteRng.Value2 = calcRng.Value2
Next pass
CleanUp:
Application.ScreenUpdating = True
Application.Calculation = previousMode
If Err.Number <> 0 Then
MsgBox "Interest solve failed: " & Err.Description, vbExclamation
ElseIf Not converged Then
MsgBox "Interest did not converge in " & MAX_PASSES & " passes.", vbExclamation
Else
MsgBox "Interest converged in " & pass & " passes.", vbInformation
End If
End Sub
Private Function MaxAbsDiff(a As Range, b As Range) As Double
Dim i As Long
Dim d As Double
Dim biggest As Double
For i = 1 To a.Cells.Count
If IsError(a.Cells(i).Value2) Or IsError(b.Cells(i).Value2) Then
Err.Raise vbObjectError + 513, , "An error value is in the interest range."
End If
d = Abs(a.Cells(i).Value2 - b.Cells(i).Value2)
If d > biggest Then biggest = d
Next i
MaxAbsDiff = biggest
End FunctionFour details matter:
- Manual calculation inside the loop. Calling
Application.Calculateonce per pass gives a predictable number of recalculations. The macro restores the user's original mode at the end, even after an error, because theCleanUplabel runs in both cases. Value2instead of copy and paste. Assigning values directly avoids the clipboard, keeps formatting intact, and is faster thanCopyandPasteSpecial. The approach is still called copy-paste because that is what it replaces by hand.- A pass limit. Without
MAX_PASSES, a model that fails to converge would loop forever. - An explicit check for error values.
Abson an error value would crash with a confusing type mismatch. Raising a clear message is better.
How fast it converges
The macro loop converges for the same reason the iterative one does. Each pass shrinks the remaining error by a factor of rate / 2. With an 8% rate, that factor is 0.04.
This Python script reproduces the macro's logic with the book example: opening balance 500, CFADS 100, rate 8%.
opening, cfads, rate = 500.0, 100.0, 0.08
pasted = 0.0 # Interest_Paste starts at zero
for i in range(1, 11):
repayment = min(opening, max(0.0, cfads - pasted))
closing = opening - repayment
calc = rate * (opening + closing) / 2 # Interest_Calc
diff = abs(calc - pasted)
print(f"pass {i}: pasted={pasted:.6f} calc={calc:.6f} diff={diff:.8f}")
if diff < 1e-6:
break
pasted = calcThe first four passes show the pattern:
| Pass | Pasted interest | Live interest | Difference |
|---|---|---|---|
| 1 | 0 | 36.0000 | 36.0000 |
| 2 | 36.0000 | 37.4400 | 1.4400 |
| 3 | 37.4400 | 37.4976 | 0.0576 |
| 4 | 37.4976 | 37.4999 | 0.0023 |
Each difference is 0.04 times the one before. With a tolerance of 0.000001 the loop stops at pass 7, and the pasted value agrees with the exact answer of 37.5 to about seven decimal places. In a realistic model with several periods, a revolver and a cash sweep, expect somewhere between 5 and 15 passes. A rate near or above 100% per period would break this convergence, but no ordinary debt schedule has one.
What you gain over iterative calculation
- No workbook-wide setting. Iterative calculation is an application-level setting that travels with the first workbook opened in a session. A user who opens your model after another file may find it off, or find it on and hiding an accidental circular reference elsewhere. The macro design needs neither.
- Errors cannot get stuck. In a live circular loop, a
#REF!or#DIV/0!feeds itself and persists after you fix the cause. Here,Interest_Pasteis a value. Fix the cause, rerun the macro, and the error is overwritten. This is why the circuit-breaker switch is often unnecessary in this design. - Control over the tolerance and the pass limit. You can set them to whatever precision the model needs.
- A visible audit trail.
Interest_Checkshows how far the model is from a consistent answer.
What you give up
- The model is no longer live. Change an input and the numbers are wrong until someone reruns the macro. This is the main source of mistakes with this design.
- Data tables and scenario tools break. An Excel data table recalculates the model for each input value but does not run your macro, so each row uses a stale
Interest_Paste. Sensitivity tables built on this design give wrong results unless the macro runs inside each scenario. - Macro-enabled files. The workbook must be saved as
.xlsm. Many organizations block macros by policy, and reviewers often distrust them. - Hard-coded cells that look like inputs. A reader seeing a pasted number among formulas may overwrite it or assume it is an assumption.
Making it harder to misuse
Three small habits reduce the risk:
- Label the paste cells. Give
Interest_Pastea distinct fill colour and a note such as "Written by SolveInterest macro. Do not type here." - Add the check to the model's checks sheet. A formula such as
=IF(MAX(ABS(Interest_Check))<0.0001, 0, 1)fed into your overall error flag makes the stale state visible, where the error flag is read by the people who consume the model. In older Excel versions, enter it as an array formula, or useSUMPRODUCT(ABS(Interest_Check))instead. - Run the macro automatically where possible. A button on the cover sheet is the minimum. Some modellers also call
SolveInterestfrom aWorkbook_BeforeSavehandler, so the saved file is always consistent. Avoid calling it fromWorksheet_ChangeorWorksheet_Calculatewithout guarding against re-entry, because the macro itself triggers recalculation and can call itself recursively.
Choosing the macro design
| Situation | Macro suitable? |
|---|---|
| Model is used by one person who understands it | Yes |
| Model needs live sensitivity or data tables | No. Prefer the algebraic solution or iterative calculation |
| Macros are blocked in your organization | No |
| Many circular loops, such as revolver, sweep and tax | Maybe. One macro can handle all of them if they share the paste range |
| Errors keep getting stuck in a live loop | Yes, this removes that problem |
| A simple unconstrained loop | No. The algebraic solution is exact and needs no loop |
The decision is usually between the macro and iterative calculation with a breaker. Choose iterative calculation if the model must stay live. Choose the macro if you cannot trust the environment's calculation settings, or if error recovery matters more than live updating.
Exercise
Your model uses the macro approach with an 8% interest rate. InterestPaste is 37.5, which is the correct answer. A colleague changes CFADS from 100 to 120 and sends you the file without running the macro. What does InterestCheck show, roughly, and what is the correct interest after running the macro? Use opening debt of 500 and average-balance interest.
Show answer
With the stale pasted interest of 37.5, repayment is 120 - 37.5 = 82.5 and the closing balance is 417.5. InterestCalc = 0.08 * (500 + 417.5) / 2 = 36.7, so InterestCheck = 36.7 - 37.5 = -0.8. The check is nonzero, which signals that the macro must be rerun. The converged answer comes from the algebraic formula: interest = 0.08 (2500 - 120) / 2 / (1 - 0.04) = 0.04 * 880 / 0.96 = 36.6667. The closing balance is 500 - 120 + 36.6667 = 416.6667. The macro reaches this within its tolerance in a few passes.
Exercise
Why can a data table give wrong sensitivity results in a model that uses the copy-paste macro, and what are two ways to avoid the problem?
Show answer
A data table recalculates the model for each input value but never runs the macro, so Interest_Paste keeps the value from the base case instead of the value that is consistent with the changed input. Two ways to avoid this are to replace the loop with the algebraic solution where it applies, so the model has no pasted cell, or to use iterative calculation with a circuit breaker, so the loop is solved live inside each data table calculation. A third option is to run the sensitivity cases from a macro that calls SolveInterest for each case and records the results.