Technical Article

Dynamic Array Spill Formulas in Delphi with HotXLS

In Excel 365, =SORT(A2:B20,2,-1) typed into D2 fills D2:E20 with the sorted table, yet the saved sheet XML carries the formula text in exactly one cell. The other 37 cells hold plain cached numbers, and the only thing tying them to D2 is a ref="D2:E20" attribute plus a metadata flag declaring "this is a dynamic array". A calculation engine reading D2 as an ordinary one-cell formula receives a single value back; when column B changes, the 37 neighbours carry on showing last run's order, and when a FILTER returns fewer rows than before, the old rows stay on the sheet beneath the new ones

What a spilled result looks like once Open returns

HotXLS reads that flag when TXLSXWorkbook.Open loads the file and treats D2 as a dynamic-array root: the cell owning the formula and the rectangle its result currently covers. The neighbours are followers. They have no formula of their own, and their values come from the root's result matrix. TXLSXWorkbook.Recalculate evaluates the root, measures the matrix it returns and lays it out from the root cell downwards and rightwards, so the spill takes whatever size today's inputs produce instead of the size Excel saved last time

Two read-only properties on TXLSXCell tell you where the spill finished up. ArrayLastRow and ArrayLastCol on the root give the bottom-right corner after the most recent recalculation, which means you never need to hard-code D2:E20 in the reading loop. Dynamic-array roots are re-evaluated on every Recalculate call, even when nothing upstream has been written, because a spill can change shape and push or release cells other formulas depend on; the incremental recalculation dependency graph is rebuilt whenever a spill's rectangle actually changes

var
  Book: TXLSXWorkbook;
  Sheet: TXLSXWorksheet;
  Root: TXLSXCell;
  r, c: Integer;
begin
  Book := TXLSXWorkbook.Create;
  try
    if Book.Open('from-customer.xlsx') <> 1 then
      Exit;
    Book.Recalculate;                     // spills resize to the current inputs
    Sheet := Book.Sheets[1];              // Sheets is 1-based
    Root := Sheet.Cells[2, 4];            // D2 holds =SORT(A2:B20,2,-1)
    if VarIsError(Root.Value) then
      Writeln('D2 did not spill: ', VarToStr(Root.Value))
    else
      for r := Root.Row to Root.ArrayLastRow do
      begin
        for c := Root.Col to Root.ArrayLastCol do
          Write(VarToStr(Sheet.Cells[r, c].Value), #9);
        Writeln;
      end;
  finally
    Book.Free;
  end;
end;

Skipping Recalculate is legitimate when all you want is what Excel computed. The followers already carry Excel's cached values, and the root's rectangle matches the ref attribute in the file. The moment your code writes an input cell, though, those cached values describe a sheet that no longer exists

Writing spill formulas in Delphi

The shortest path is the ordinary cell API. Assigning TXLSXCell.Formula compiles the text, and when the formula's outermost result is an array, HotXLS marks the cell as a dynamic-array root and adds the same metadata Excel writes. That detection takes in the array-returning built-ins: FILTER, SORT, SORTBY, UNIQUE, SEQUENCE, RANDARRAY, XLOOKUP, the shaping family (VSTACK, HSTACK, TAKE, DROP, CHOOSEROWS, CHOOSECOLS, EXPAND, TOROW, TOCOL, WRAPROWS, WRAPCOLS), TEXTSPLIT, and the LAMBDA helpers MAP, SCAN, MAKEARRAY, BYROW and BYCOL. An operator applied to a multi-cell range, as in =D2:D13*1.1, counts as well. XMATCH spills when its lookup value is itself a range, and LET spills when its final expression does

That is a different contract from the scalar statistical distribution functions, which hand back one number per call and never trouble a neighbour. All of the functions above run through a single evaluator branch and return a two-dimensional matrix, and the spill logic is indifferent to which function produced it

TXLSXRange.SetDynamicArrayFormula is the explicit form. Pass it a range whose top-left cell is the root; the rest of the range is merely a starting rectangle, because the next Recalculate resizes it to the true result. Reach for it when the detector cannot see the array from the formula text, which is the usual case for a function you registered yourself through the custom worksheet functions hook: the engine knows the built-in names, not what your callback will return. Such a function has to return a two-dimensional variant array if it is to spill

var
  Book: TXLSXWorkbook;
  Sheet: TXLSXWorksheet;
  r: Integer;
begin
  Book := TXLSXWorkbook.Create;
  try
    Sheet := Book.Sheets.Add('Orders');
    for r := 2 to 20 do
    begin
      Sheet.Cells[r, 1].Value := 'Item ' + IntToStr((r mod 7) + 1);
      Sheet.Cells[r, 2].Value := r * 37 mod 250;
    end;
    // Built-in array functions are detected on assignment
    Sheet.Cells[2, 4].Formula := '=SORT(A2:B20,2,-1)';       // spills D2:E20
    Sheet.Cells[2, 7].Formula := '=UNIQUE(A2:A20)';          // spills down from G2
    // Explicit form: I2 is the root, the size comes from the result
    Sheet.Range['I2'].SetDynamicArrayFormula(
      '=FILTER(A2:B20,B2:B20>100,"none")');
    Book.Recalculate;
    Book.SaveAs('orders-sorted.xlsx');
  finally
    Book.Free;
  end;
end;

The saved file receives t="array", a ref matching the computed rectangle, and the dynamic-array cell metadata, so Excel 365 opens D2 as a live spill with cached values already in place. The formula text uses commas between arguments, which is what Excel stores; the HotXLS parser also accepts semicolons, so formula strings copied from a European-locale formula bar compile unchanged

Why does a spill return #SPILL!?

A spill returns #SPILL! when the rectangle it needs is not free. HotXLS checks every target cell apart from the root before writing anything, and the spill is refused when one of them holds a value or a formula, carries rich text, or belongs to another array. The rectangle likewise may not overlap a merged range or an Excel table, and it may not run beyond the last row or column of the worksheet. These are Excel's rules, and matching them is the whole point: a file showing numbers in your service and #SPILL! in the customer's Excel is worse than one failing in both places

When the check fails, the root cell takes the error value and its ArrayLastRow and ArrayLastCol collapse onto the root itself. The blocking cell is left untouched. Two other errors look similar yet mean something else: a result that is not a two-dimensional matrix becomes #CALC!, and so does a FILTER matching no rows, unless you passed its third if_empty argument the way the FILTER in I2 above does

// G2 holds =UNIQUE(A2:A20). Someone typed a label two rows under it
Sheet.Cells[5, 7].Value := 'Total';
Book.Recalculate;
if VarIsError(Sheet.Cells[2, 7].Value) then
  // #SPILL!: G5 is in the way, nothing below G2 was overwritten
  Sheet.Cells[5, 7].Value := Null;   // clear the landing zone
Book.Recalculate;                    // G2 now spills over G2:G8

Shrinking is handled on the same pass. When a FILTER that returned 40 rows yesterday returns 25 today, the 15 cells belonging solely to the old spill are released and their cached values cleared, so nothing from yesterday's result survives beneath the new one. Only cells without a formula of their own that this root filled are cleared

Keep the area below and to the right of every spill root empty in the templates you generate. A label placed directly beneath a FILTER works until the data grows by one row, and then the whole block turns into a single error. Put totals above the root, or in a column the spill cannot reach

Fixed rectangles: SetArrayFormula and the older CSE arrays

TXLSRange.SetArrayFormula on the classic engine and TXLSXRange.SetArrayFormula on the XLSX engine write the older kind of array formula, the {=...} block that predates dynamic arrays and was entered with Ctrl+Shift+Enter over a pre-selected range. The formula is stored once, in the top-left cell, and every other cell in the rectangle points back to it. The difference from a dynamic array is that the rectangle forms part of the formula's definition: Recalculate fills it and never shifts its border

Diagram of a HotXLS dynamic array spill in Delphi: SetArrayFormula anchors =SEQUENCE(3;2;1;1) on A1:B3, where the root cell owns the compiled formula and the member cells take values 1 through 6
SetArrayFormula pins down a 3-by-2 block: the formula lives in root cell A1 and every other cell in the rectangle points back to it

That fixed border decides what happens when the result and the rectangle disagree. A result larger than the rectangle is cut off at the edge; with a smaller one, the extra cells stay empty. A single value is repeated into every cell, as Excel does

// A 3-by-2 result into a 3-by-2 block: 1..6, filled row by row
Sheet.Range['A1:B3'].SetArrayFormula('=SEQUENCE(3,2,1,1)');
// Four results into two cells: D1 = 1, D2 = 2, the rest is dropped
Sheet.Range['D1:D2'].SetArrayFormula('=SEQUENCE(4)');
Book.Recalculate;
// Inserting a row between A1 and A3 raises an exception:
// a structural edit may move or delete a whole CSE block, never cut through it
// Sheet.InsertRows(2, 1);
Decision flow showing how a HotXLS Delphi spill fills the anchored rectangle exactly, and what befalls a result larger than the range passed to SetArrayFormula
A block anchored with SetArrayFormula keeps its size; only a dynamic-array root grows, shrinks or reports #SPILL! in the Excel 365 manner

For new work, write dynamic arrays. Use SetArrayFormula when the surrounding layout is fixed and must not budge, a formatted template with a footer three rows below the block for instance, or when you are rebuilding an array that already arrived in the file as a CSE block. Excel rejects structural edits cutting through part of a CSE array, and HotXLS raises an exception from InsertRows or DeleteRows in the same situation instead of resizing the block. Dynamic spills carry no such restriction; an insert releases the old followers and the next Recalculate lays the result out afresh

Element-wise operators and the rule of shape

When either side of +, -, *, / or ^ is an array, HotXLS applies the operator element by element. Comparison operators and & take the same path, so =B2:B20>100 yields a column of TRUE and FALSE, precisely the kind of mask FILTER expects as its second argument

Diagram of element-wise array broadcasting in HotXLS for Delphi: a scalar multiplier applied to every element of D2:D13, and two equal-shaped ranges multiplied element by element
Arithmetic operators broadcast a scalar across every element and multiply equal-shaped arrays element by element

The shape rule is short. In each dimension the two operands must either share the same length or one of them has length 1, which is stretched to match the other side. A scalar therefore reaches every element, two 12-row columns pair up row by row, and a 12-by-1 column times a 1-by-3 row produces a 12-by-3 grid. Any other combination, a 12-row column against a 10-row column say, evaluates to #VALUE! for the whole formula, so make sure both ranges cover the same rows. Errors stay local: a zero in E7 turns only the matching element of =D2:D13/E2:E13 into #DIV/0!, and the other eleven results are computed normally

With prices in D2:D13 and quantities in E2:E13, assigning =D2:D13*1.1 to F2 spills F2:F13, =D2:D13*E2:E13 in G2 spills the twelve pairwise products, and =D2:D13*{1,1.1,1.2} in I2 fills I2:K13 with three price tiers per row. Each of these is detected as a dynamic array on assignment, so no extra call is needed before Recalculate

The array operator formulas and implicit intersection article covers the one-cell case, where a formula such as =SUM(A1:B1*{10,100}) reduces an array to a single number yet still has to be stored as a dynamic array so Excel does not insert @

The @, the # and intersections in formula text

Three pieces of syntax turn up in workbooks that use dynamic arrays, and HotXLS parses all of them. A leading @, as in =@A2:A20, is Excel 365's implicit intersection: it reduces the range to the cell on the formula's own row (or column, for a horizontal range) and stops the formula from spilling. A trailing #, as in =SUM(D2#), refers to whatever rectangle the spill rooted at D2 currently covers, so a total over a FILTER result follows the result as it grows and shrinks. When the root has no valid spill, D2# returns the same error the root shows

In the file neither symbol appears literally. Excel stores @X as a call to SINGLE(X) and X# as ANCHORARRAY(X), and HotXLS translates between those storage forms and the @ and # notation you type. The older range-intersection operator still works too: =A1:A3 B1:B3, with a space between two references, returns the cell where the ranges cross, and HotXLS keeps the exact run of spaces so the formula text round-trips unchanged. An @ written between two references, A1:A3 @ B1:B3, is read as that same intersection

The dynamic-array functions, the spill sizing and the #SPILL! checks described here form part of the formula engine in the HotXLS Delphi Excel Component; its formula reference lists every supported function together with the argument modes each one accepts