Technical Article

Live Cross-Workbook Formulas in Delphi with HotXLS

A valuation workbook carries =[Rates.xlsx]FX!B4*C10 in cell D10. The treasury team updated the rate table this morning, yet a batch job that opens valuation.xlsx and recalculates it still prints yesterday's figure, and recalculating a second or third time prints the same number. The rate in that formula is read from a copy of FX!B4 held inside valuation.xlsx itself, written the last time Excel refreshed the link, and that copy only changes when something hands the real rate table to the calculation

Excel keeps external references in a form that survives without the companion file. The workbook stores a table of supporting books in its externalLink parts (the SpreadsheetML external workbook structure in ECMA-376), every formula token that leaves the workbook points into that table by index, and each externalLink part carries a sheetDataSet with the last known value of every referenced cell. That is why a file opened without its companions still shows numbers. A library evaluating such a formula on its own has nowhere else to look

Registering the rate table with RegisterExternalWorkbook

HotXLS lets the calling application supply the missing workbook. TXLSXWorkbook.RegisterExternalWorkbook takes a book name and an open TXLSXWorkbook; from then on every formula in the main workbook that refers to that book reads its cells from the object in memory, and the cache held in the file is consulted only for books nobody registered. UnregisterExternalWorkbook removes the entry again

uses
  SysUtils, Variants, lxHandleX;

var
  Main, Rates: TXLSXWorkbook;
begin
  Main := TXLSXWorkbook.Create;
  Rates := TXLSXWorkbook.Create;
  try
    if (Main.Open('valuation.xlsx') <> 1) or
       (Rates.Open('rates.xlsx') <> 1) then
      Exit;

    // D10 on the first sheet holds =[Rates.xlsx]FX!B4*C10
    // Sheets and Cells are both 1-based
    Main.Recalculate;
    Writeln('from cache: ', VarToStr(Main.Sheets[1].Cells[10, 4].Value));

    Main.RegisterExternalWorkbook('Rates.xlsx', Rates);
    Main.Recalculate;
    Writeln('live:       ', VarToStr(Main.Sheets[1].Cells[10, 4].Value));
  finally
    Main.UnregisterExternalWorkbook('Rates.xlsx');
    Rates.Free;
    Main.Free;
  end;
end;

The two Writeln calls are the quickest way to confirm that the registration took. If both print the same value while rates.xlsx clearly holds a different rate, the name matched no link in valuation.xlsx and evaluation kept reading the cache. Unregistering a name that was never registered is harmless, which is why the call can sit in the finally block even when Open failed

How the book name is matched

Matching is case-insensitive and runs against the link targets recorded in the main workbook. Square brackets and enclosing quotes are stripped, backslashes and forward slashes count as the same separator, and a relative target resolves against the main workbook's folder. A bare file name such as Rates.xlsx therefore matches a link whose target is C:\Treasury\Rates.xlsx, which is what most callers want. Three cases catch people out:

  • The extension is part of the name. Registering 'Rates' is accepted, matches no link, and every formula keeps reading the cache
  • Two links with the same file name in different folders make a bare name ambiguous, and RegisterExternalWorkbook raises EXLSWorkspaceIdentityConflict; passing the full target instead settles it
  • One TXLSXWorkbook object can be registered once. When two links reach the same file through different paths, a mapped drive and a UNC share for instance, register it under one target and add the other spelling with Main.ExternalWorkspace.AddAlias; a second RegisterExternalWorkbook call for the same object raises EXLSWorkspaceDuplicateWorkbook

An empty name, a nil workbook, or the main workbook itself is ignored without an exception. The exception classes live in the lxWorkbookWorkspace unit

Why does editing Rates.xlsx not update the main workbook by itself?

Nothing crosses the workbook boundary until the main workbook recalculates. A value written into Rates marks cells dirty inside Rates only, because the main workbook's dependency graph holds no entries for another workbook's cells. What makes the next Main.Recalculate pick the change up is how HotXLS files formulas that point outside the workbook: their source cells cannot be placed in the graph, so those formulas are treated like volatile ones and re-evaluated on every pass, together with everything downstream of them

That is the correct default for this kind of reference, and it has a cost. A model with a few hundred external lookups re-evaluates those cells and their dependents on every pass, even when no source changed. The rest of the workbook still recalculates incrementally

The second trap sits on the source side. The live lookup reads the value currently stored in the referenced cell of Rates. When FX!B4 is a typed number, writing it and recalculating the main workbook is enough. When FX!B4 is itself a formula over an input in FX!B2, writing B2 changes nothing the main workbook can see until Rates recalculates, because Main.Recalculate never recalculates the workbooks it reads from. Sources go first:

procedure RunScenarios(Main, Rates: TXLSXWorkbook;
  const SpotRates: array of Double);
var
  FX: TXLSXWorksheet;
  I: Integer;
begin
  FX := Rates.Sheets.SheetByName('FX');
  if FX = nil then
    Exit;
  Main.RegisterExternalWorkbook('Rates.xlsx', Rates);
  try
    for I := 0 to High(SpotRates) do
    begin
      FX.Cells[2, 2].Value := SpotRates[I];  // B2: the input
      Rates.Recalculate;                     // B4 is a formula over B2
      Main.Recalculate;                      // re-reads [Rates.xlsx]FX!B4
      Writeln(Format('%.4f -> %s',
        [SpotRates[I], VarToStr(Main.Sheets[1].Cells[10, 4].Value)]));
    end;
  finally
    Main.UnregisterExternalWorkbook('Rates.xlsx');
  end;
end;

Rates stays in memory for the whole loop, so no file is written or reopened between scenarios. Each scenario costs one recalculation of each workbook, and on the Rates side the engine described in incremental recalculation and the dependency graph re-evaluates only the cells downstream of B2

What happens when a reference cannot be resolved?

Resolution runs in a fixed order. A registered, still-open workbook wins. Failing that, the formula reads the external-link cache held in the file, and a cell the cache does not list reads as empty, which is also what Excel shows for an uncached cell of a broken link. A real error comes from a narrower set of cases: the book name matches more than one registration, the registered workbook has no sheet with the referenced name, or the file carries no link record for that book. Sheets in the live workbook are found by name, so renaming the FX tab in rates.xlsx breaks the reference even though the sheet never moved

Resolution paths of a HotXLS cross-workbook formula in Delphi: a workbook registered through RegisterExternalWorkbook supplies fresh cells on Recalculate, an unregistered book falls back to the external-link cache, and a reference that cannot be resolved leaves the cell's last computed value in place
Registration reads cells from the live object, the cache fallback keeps unregistering safe, and an unresolvable reference leaves the last good value in place

When a formula that refers to another workbook evaluates to an error, HotXLS does not write that error over a value the cell already holds. The cell keeps its last computed value until a later pass succeeds. A cell that has never held a value does receive the error, so a freshly written formula with an unresolvable reference shows #REF! instead of a misleading blank

Writing errors through would be the more literal behaviour, and we think it is the worse one for batch work. A rate table that is briefly unavailable would turn every dependent cell into an error marker, the next good run would have to repair all of them, and a report saved in between would go out full of #REF!. Keeping the last good value means an interrupted pipeline still produces a document that reads sensibly. The price is that the document stops telling anyone which values are current, a point the last section comes back to

HotXLS never takes ownership of a registered workbook and never frees it. Freeing it yourself is allowed: the registration goes dead with the object, the next lookup drops it, and those formulas fall back to the cache. Calling UnregisterExternalWorkbook before Free is still the cleaner habit, because the switch back to cached values then shows up as a line in your code rather than as a side effect of a Free in some other unit

Finding the book names a file expects

TXLSXWorkbook.AnalyzeFormulaIssues reports missing functions, external references and circular dependency components in one pass. Each formula that reaches into another book produces an entry of kind xlsxFormulaIssueExternalReference carrying the 1-based Sheet, Row and Col, the Formula text, and ExternalWorkbook set to the link target recorded in the file. Register under that target. It matches its link exactly, it never collides with a same-named file in another folder, and it shows where Excel last found the companion, which is usually the first place to look for it

The routine below registers every companion it can find, recalculates, and lists the external-reference cells whose fresh value differs from the value the file carried. LocateCompanion and SameCellValue are not HotXLS functions; they stand for code you write yourself. The first maps a link target to an opened workbook (a folder search, a table of approved rate files), the second compares two Variants with whatever tolerance your figures need

uses
  Classes, SysUtils, Variants, lxHandleX;

procedure ReportStaleExternalValues(Main: TXLSXWorkbook);
var
  Issues: TArray<TXLSXFormulaIssue>;
  Cached: array of Variant;
  Targets: TStringList;
  Book: TXLSXWorkbook;
  I: Integer;
begin
  Issues := Main.AnalyzeFormulaIssues;
  SetLength(Cached, Length(Issues));
  Targets := TStringList.Create;
  try
    Targets.Sorted := True;
    Targets.CaseSensitive := False;
    Targets.Duplicates := dupIgnore;
    for I := 0 to High(Issues) do
      if Issues[I].Kind = xlsxFormulaIssueExternalReference then
      begin
        Cached[I] := Main.Sheets[Issues[I].Sheet]
          .Cells[Issues[I].Row, Issues[I].Col].Value;
        Targets.Add(Issues[I].ExternalWorkbook);
      end;

    for I := 0 to Targets.Count - 1 do
    begin
      Book := LocateCompanion(Targets[I]);  // your own lookup
      if Book <> nil then
        Main.RegisterExternalWorkbook(Targets[I], Book)
      else
        Writeln('not available, cache stays in use: ', Targets[I]);
    end;

    Main.Recalculate;
    for I := 0 to High(Issues) do
      if (Issues[I].Kind = xlsxFormulaIssueExternalReference) and
         not SameCellValue(Cached[I],  // your own comparison
           Main.Sheets[Issues[I].Sheet]
             .Cells[Issues[I].Row, Issues[I].Col].Value) then
        Writeln(Format('sheet %d R%dC%d %s is stale',
          [Issues[I].Sheet, Issues[I].Row, Issues[I].Col,
           Issues[I].Formula]));
  finally
    for I := 0 to Targets.Count - 1 do
      Main.UnregisterExternalWorkbook(Targets[I]);
    Targets.Free;
  end;
end;

A formula that refers to two books appears twice in the result, once per book, and many formulas share one book, which is why the targets pass through a de-duplicating list before registration. Registering the same workbook object a second time raises EXLSWorkspaceDuplicateWorkbook

The built-in CalculateAndVerify check does not replace this routine. It skips volatile formulas so that NOW and RAND do not flood the report, and formulas pointing at another workbook count as volatile, so a stale external value never surfaces as a mismatch there. Snapshotting the cells before Recalculate is the comparison that actually catches it

Consolidation, scenarios and loading on demand

Consolidation is the obvious fit. A group workbook references twelve monthly files: open the twelve, register each under the target AnalyzeFormulaIssues reports, recalculate once, and read the consolidated figures on a machine without Excel. The scenario loop shown earlier is the second shape, and the stale-value report is the third, run just before a file goes to a client

Three shapes of live cross-workbook evaluation with HotXLS in Delphi: consolidation across twelve monthly files, scenario analysis that never writes a file between runs, and validation comparing recalculated results against the cached values a file carries
Consolidation registers every monthly file and recalculates once, scenario loops never touch disk, and validation compares fresh results against the cache a client would have received

When the set of companions is not known up front, Main.ExternalWorkspace.OnLoadWorkbook lets the workspace ask for a book the first time a formula needs it. The handler receives the requested identity in ARequest.Identity, opens the file, keeps the TXLSXWorkbook alive somewhere the application controls, and hands it back as AResponse.Workbook := Book.CreateWorkspaceWorkbook with AResponse.Status := xlswlrsResolved. Returning xlswlrsNotFound sends the formula back to the cache. A failed request is remembered instead of being retried for every cell that names the same book; ResetLoadAttempts clears that memory, and MaxLoadDepth and MaxWorkbookCount (16 and 64 by default) cap nested loads and the number of books the workspace will hold

For a one-off comparison of what changed between two saved versions of a workbook, rather than whether one file's cache is stale, diffing two Excel workbooks is the better tool

A workbook whose companions you cannot supply is best treated as read-only. Recalculating it keeps the cached values, but an edit that feeds a dependent cell leaves a document where some numbers are current and some are historic, with nothing in the file to mark which is which. Copying formulas from one workbook into another follows its own rebinding rules, covered in cross-workbook copy and formula rebinding, and names that point into other books add the layer described in defined names and cross-sheet formulas

Live external evaluation, the incremental engine behind Recalculate and the formula analysis used above ship in the same library for Delphi and C++Builder; the HotXLS Delphi spreadsheet component page covers the rest of the engine