# Formulas

> Formula syntax, references, cross-sheet references, defined names, LET and LAMBDA, custom functions, dynamic arrays and spilling, errors, circular references and volatile functions.

Formulas follow Excel's syntax and semantics: the same references, operators, precedence, type coercion and error propagation, and the same 1900 date system. A workbook built here behaves like the same workbook in Excel, and [xlsx files](https://docs.birchui.com/spreadsheet/xlsx.md) move between the two with their formulas intact.

**Live demo: Loan amortisation sheet** (runs on the HTML version of this page). Source of `demos/spreadsheet-loan.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createSpreadsheet } from '@birchui/spreadsheet';
import { docsTheme, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'Loan amortisation sheet', height: 560 };

const money = { numberFormat: '#,##0.00' };
const header = { bold: true, fill: '#1f3a5f', color: '#ffffff' };

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  toolbar.append('Change the principal, rate or term in column B; the payment and all 360 schedule rows recalculate.');
  const sheet = createSpreadsheet(body, {
    theme: docsTheme(),
    height: '100%',
    data: {
      version: 1,
      sheets: [
        {
          name: 'Loan',
          freeze: { rows: 6, columns: 0 },
          columnWidths: { A: 90, B: 130, C: 130, D: 130, E: 150 },
          cells: {
            A1: { value: 'Principal' },
            B1: { value: 250000, style: money },
            A2: { value: 'Annual rate' },
            B2: { value: 0.0625, style: { numberFormat: '0.00%' } },
            A3: { value: 'Years' },
            B3: { value: 30 },
            A4: { value: 'Payment' },
            B4: { formula: '=PMT(B2/12, B3*12, -B1)', style: { ...money, bold: true } },
            D1: { value: 'Total interest' },
            E1: { formula: '=B4*B3*12-B1', style: money },
            A6: { value: 'Month', style: header },
            B6: { value: 'Payment', style: header },
            C6: { value: 'Interest', style: header },
            D6: { value: 'Principal', style: header },
            E6: { value: 'Balance', style: header },
            A7: { formula: '=SEQUENCE(B3*12)' },
          },
        },
      ],
    },
  });
  const rows = 360;
  const schedule = Array.from({ length: rows }, (_, i) => {
    const r = i + 7;
    return [
      `=IF(A${r}="","",$B$4)`,
      `=IF(A${r}="","",IPMT($B$2/12, A${r}, $B$3*12, -$B$1))`,
      `=IF(A${r}="","",B${r}-C${r})`,
      `=IF(A${r}="","",$B$1-SUM($D$7:D${r}))`,
    ];
  });
  sheet.setRange(`B7:E${rows + 6}`, schedule);
  sheet.setStyle(`B7:E${rows + 6}`, money);

  const offs = [
    sheet.on('cellChange', ({ address, newValue, source }) => {
      if (source !== 'edit' && source !== 'paste') return;
      status.textContent = `${address} = ${String(newValue)}. Monthly payment is now ${sheet.getDisplayText('B4')}.`;
    }),
    sheet.on('recalculated', (event) => {
      if ('durationMs' in event && typeof event.durationMs === 'number') {
        status.textContent = `Recalculated in ${event.durationMs.toFixed(1)} ms. Payment ${sheet.getDisplayText('B4')}.`;
      }
    }),
  ];
  status.textContent = `Monthly payment ${sheet.getDisplayText('B4')}, total interest ${sheet.getDisplayText('E1')}.`;
  const stopTheme = onDocsThemeChange((theme) => sheet.update({ theme }));
  return () => {
    for (const off of offs) off();
    stopTheme();
    sheet.destroy();
  };
}
```

## Entering values and formulas

What a user types, or what you pass to `setValue()` and `setRange()`, is interpreted the way Excel interprets typed input:

| Input | Stored as |
| --- | --- |
| `=PMT(B2/12, B3*12, -B1)` | A formula. Anything that starts with `=`. |
| `1250`, `-3.5`, `1.2E+05` | A number. |
| `1,250.75` | The number 1250.75, formatted `#,##0.00`. |
| `6.25%` | The number 0.0625, formatted `0.00%`. |
| `$1,539.29` | The number 1539.29, formatted as currency. |
| `3/15/2026`, `2026-03-15`, `15-Mar-2026` | A date serial, formatted as a date. Slash dates are read month first, so `3/4/2026` is 4 March. |
| `9:30`, `2:45 PM` | A time, as a fraction of a day. |
| `TRUE`, `false` | A boolean. |
| `#N/A` | That error value. |
| `'00742` | The text `00742`. A leading apostrophe keeps anything as text. |
| Anything else | Text. |

`setFormula(address, formula)` always stores a formula, adding the `=` if you leave it out.

## References

| Syntax | Meaning |
| --- | --- |
| `B4` | A relative reference. It shifts when the formula is copied or filled. |
| `$B$4`, `$B4`, `B$4` | Absolute column and row, or one of them. Press `F4` while editing to cycle. |
| `B2:E366` | A range. |
| `A:A`, `A:C` | Whole columns. |
| `7:7`, `7:366` | Whole rows. |
| `Inputs!B2`, `'Q3 Budget'!B2:B40` | A cell or range on another sheet. Quote sheet names with spaces or punctuation, and double an apostrophe inside a name: `'Owner''s draw'!A1`. |
| `Jan:Dec!B5`, `'Q1 North:Q1 South'!B2:B40` | A 3-D reference: the same cell or range on every sheet from the first to the last, in tab order. See [3-D references](#3-d-references). |
| `F2#` | The spill range of the dynamic array formula in `F2`. See [Dynamic arrays and spilling](#dynamic-arrays-and-spilling). |
| `A1:C10 B5:E5` | Intersection: the cells both ranges share, here `B5:C5`. |
| `(A1:A10, C1:C10)` | Union: both ranges as one argument, as in `SUM((A1:A10, C1:C10))`. |
| `@A1:A10` | Implicit intersection: the value in the formula's own row or column. |
| `{1, 2, 3; 4, 5, 6}` | An array constant. Commas separate columns and semicolons separate rows. |

When rows, columns or sheets change, references follow, as in Excel:

- Inserting rows or columns inside a referenced range grows the range; inserting before it shifts it.
- Deleting rows or columns that a formula refers to turns that reference into `#REF!`.
- Renaming a sheet rewrites every reference to it, adding quotes when the new name needs them.
- Cut and paste moves the cells and updates every formula that pointed at them. Copy and paste, and the fill handle, shift relative references.

### 3-D references

`=SUM(Jan:Dec!B5)` adds `B5` on `Jan`, `Dec` and every sheet between them. Use a 3-D reference as an argument of a function that takes several ranges, such as `SUM`, `AVERAGE`, `COUNT`, `COUNTA`, `MAX`, `MIN`, `PRODUCT`, `STDEV` and `VAR`. Where one value is needed, as in `=Jan:Dec!B5+1`, the result is `#VALUE!`.

- A sheet added or moved between the two end sheets joins the reference, and one moved out leaves it.
- Renaming an end sheet rewrites the reference. Deleting an end sheet shrinks the reference to the next sheet inside it; deleting the last sheet it covers gives `#REF!`.
- Inserting or deleting rows and columns on one sheet does not shift a 3-D reference.
- A name that is not a sheet gives `#REF!`.

### R1C1 notation

Formulas are stored and typed in A1 notation. `formulaToR1C1()` and `formulaFromR1C1()` convert a formula to and from R1C1 notation relative to the cell that holds it, for tools that compare or generate formulas:

```ts
import { formulaFromR1C1, formulaToR1C1 } from '@birchui/spreadsheet';

formulaToR1C1('=SUM(A1:B2)+$C$3*C4', 'D7'); // '=SUM(R[-6]C[-3]:R[-5]C[-2])+R3C3*R[-3]C[-1]'
formulaFromR1C1('=RC[-1]*R1C1', 'D7'); // '=C7*$A$1'
```

Whole rows and columns are written with an explicit offset (`C[0]`, `R[0]:R[1]`); a bare `R` or `C` is read as a name. The component has no R1C1 display mode, and `INDIRECT` accepts R1C1 text when its second argument is `FALSE`.

## Operators

From highest to lowest precedence, as in Excel:

| Operators | Meaning |
| --- | --- |
| `:` (range), space (intersection), `,` (union) | Reference operators. |
| `-` | Negation. `-2^2` is 4, as in Excel. |
| `%` | Percent: `25%` is 0.25. |
| `^` | Exponent. Evaluated left to right, so `2^3^2` is 64. |
| `*`, `/` | Multiplication and division. |
| `+`, `-` | Addition and subtraction. |
| `&` | Text concatenation: `A2 & ", " & B2`. |
| `=`, `<>`, `<`, `<=`, `>`, `>=` | Comparison. Text comparison is case-insensitive. |

Types convert as in Excel: `"5" + 1` is 6, `TRUE + 1` is 2, an empty cell is 0 in arithmetic and `""` in text, and text that is not a number gives `#VALUE!` in arithmetic.

## Functions

501 worksheet functions are built in, across math, statistics, engineering, database, logic, lookup, text, date and time, financial and information categories, with the names and argument order Excel uses. The [function reference](https://docs.birchui.com/spreadsheet/functions.md) lists each one with its syntax, and `listFunctions()` returns the same list at runtime, for example for your own autocomplete.

A few examples of what is available:

| Need | Functions |
| --- | --- |
| Lookups | [`XLOOKUP`](https://docs.birchui.com/spreadsheet/functions.md#xlookup), [`XMATCH`](https://docs.birchui.com/spreadsheet/functions.md#xmatch), [`INDEX`](https://docs.birchui.com/spreadsheet/functions.md#index), [`MATCH`](https://docs.birchui.com/spreadsheet/functions.md#match), [`VLOOKUP`](https://docs.birchui.com/spreadsheet/functions.md#vlookup) |
| Conditional totals | [`SUMIFS`](https://docs.birchui.com/spreadsheet/functions.md#sumifs), [`COUNTIFS`](https://docs.birchui.com/spreadsheet/functions.md#countifs), [`AVERAGEIFS`](https://docs.birchui.com/spreadsheet/functions.md#averageifs), [`MAXIFS`](https://docs.birchui.com/spreadsheet/functions.md#maxifs) |
| Loans and investments | [`PMT`](https://docs.birchui.com/spreadsheet/functions.md#pmt), [`IPMT`](https://docs.birchui.com/spreadsheet/functions.md#ipmt), [`PPMT`](https://docs.birchui.com/spreadsheet/functions.md#ppmt), [`NPV`](https://docs.birchui.com/spreadsheet/functions.md#npv), [`XIRR`](https://docs.birchui.com/spreadsheet/functions.md#xirr) |
| Dates | [`EDATE`](https://docs.birchui.com/spreadsheet/functions.md#edate), [`EOMONTH`](https://docs.birchui.com/spreadsheet/functions.md#eomonth), [`NETWORKDAYS`](https://docs.birchui.com/spreadsheet/functions.md#networkdays), [`WORKDAY`](https://docs.birchui.com/spreadsheet/functions.md#workday), [`DATEDIF`](https://docs.birchui.com/spreadsheet/functions.md#datedif) |
| Text | [`TEXTSPLIT`](https://docs.birchui.com/spreadsheet/functions.md#textsplit), [`TEXTJOIN`](https://docs.birchui.com/spreadsheet/functions.md#textjoin), [`TEXTBEFORE`](https://docs.birchui.com/spreadsheet/functions.md#textbefore), [`TEXT`](https://docs.birchui.com/spreadsheet/functions.md#text) |

Function names are case-insensitive. Unknown names give `#NAME?`. To add your own, see [Custom functions](#custom-functions).

## Defined names

A defined name gives a cell, a range, a constant or a formula a readable name, so `=B1*B2` becomes `=Principal*MonthlyRate`.

```ts
sheet.defineName('Principal', '=Loan!$B$1');
sheet.defineName('MonthlyRate', '=Loan!$B$2/12');
sheet.defineName('VatRate', '=0.2');
sheet.defineName('Deposit', '=Loan!$B$8', 'Loan');

sheet.setFormula('B4', '=PMT(MonthlyRate, Years*12, -Principal)');
```

- Without a sheet argument, a name is workbook-wide. With one, it is scoped to that sheet and takes precedence there over a workbook name of the same name.
- Names start with a letter, underscore or backslash and contain letters, digits, underscores and periods. A name that looks like a cell address, such as `TAX1`, is rejected.
- Names are stored in the workbook JSON under `names`, and exported to and imported from xlsx.
- Type a name into the name box to select the range it refers to.

## Structured references

Formulas can refer to [tables](https://docs.birchui.com/spreadsheet/tables.md) by name instead of by address, so they keep working as rows are added:

```ts
sheet.setFormula('H2', '=SUM(Orders[Amount])');
sheet.setFormula('H3', '=AVERAGE(Orders[[#Data],[Units]:[Unit Price]])');
sheet.setFormula('E2', '=[@Units]*[@[Unit Price]]');
```

| Reference | Refers to |
| --- | --- |
| `Orders` or `Orders[]` | The data rows of the table |
| `Orders[Amount]` | The data rows of one column |
| `Orders[[Units]:[Amount]]` | The data rows of a run of columns |
| `Orders[#All]`, `Orders[#Headers]`, `Orders[#Data]`, `Orders[#Totals]` | The whole table, the header row, the data rows or the totals row |
| `Orders[[#Headers],[Amount]]` | The header cell of one column |
| `Orders[@Amount]` or `Orders[[#This Row],[Amount]]` | The cell in the formula's own row |
| `[@Amount]`, `[Amount]` | The same, inside the table that contains the formula |

- Table and column names are case-insensitive. Put a column name in an extra pair of brackets when it contains spaces or punctuation (`[@[Unit Price]]`), and escape `[`, `]`, `#` and `'` with a leading `'`.
- An unknown table or column gives `#REF!`. A this-row reference used outside the table's data rows gives `#VALUE!`.
- Renaming a table, or changing a header cell, rewrites every formula that refers to it. Converting a table to a range rewrites its references as absolute A1 references.
- `INDIRECT("Orders[Amount]")` resolves structured references too.

## LET and LAMBDA

`LET` names intermediate results inside one formula, so a long formula computes each part once and stays readable:

```text
=LET(monthly, B2/12, months, B3*12, PMT(monthly, months, -B1))
```

`LAMBDA` creates a function. Call it inline, or save it as a defined name to create a custom function for the whole workbook:

```ts
sheet.defineName('LineTotal', '=LAMBDA(qty, price, discount, qty * price * (1 - discount))');
sheet.setFormula('F2', '=LineTotal(C2, D2, E2)');
```

```text
=LAMBDA(x, x * 1.2)(B5)
=MAP(B2:B13, LAMBDA(amount, ROUND(amount * 1.2, 2)))
=REDUCE(0, C2:C50, LAMBDA(total, value, total + MAX(value, 0)))
=BYROW(B2:M20, LAMBDA(month, SUM(month)))
```

`MAP`, `REDUCE`, `SCAN`, `BYROW`, `BYCOL` and `MAKEARRAY` take a `LAMBDA` as their last argument. `LET` and `LAMBDA` are part of the formula language rather than ordinary functions, so they do not appear in `listFunctions()` or the function reference.

Where a `LAMBDA` is expected, the name of a function works too: `=BYROW(B2:M20, SUM)` is the same as the last example. The named function receives the arguments the helper passes, so it has to accept that many.

## Grouping with formulas

`GROUPBY` and `PIVOTBY` summarise rows with a formula that spills, without a pivot table:

```text
=GROUPBY(A2:A500, D2:D500, SUM)
=GROUPBY(A1:B500, D1:E500, AVERAGE, 3, 2, -3)
=PIVOTBY(A2:A500, C2:C500, D2:D500, SUM)
=PIVOTBY(A2:A500, C2:C500, D2:D500, PERCENTOF, 0, 1, , 1, , B2:B500="Laptop", 2)
```

```text
GROUPBY(row_fields, values, function, [field_headers], [total_depth], [sort_order], [filter_array], [field_relationship])
PIVOTBY(row_fields, col_fields, values, function, [field_headers], [row_total_depth], [row_sort_order],
        [col_total_depth], [col_sort_order], [filter_array], [relative_to])
```

| Argument | Meaning |
| --- | --- |
| `row_fields`, `col_fields` | One or more columns to group by. All ranges must have the same number of rows. |
| `values` | One or more columns to aggregate. Each is aggregated on its own. |
| `function` | A function name such as `SUM`, `AVERAGE`, `COUNT`, `COUNTA`, `MAX`, `MIN`, `MEDIAN`, `PRODUCT`, `CONCAT`, `ARRAYTOTEXT` or `PERCENTOF`, or a `LAMBDA`. A `LAMBDA` with one parameter receives the values of the group; with two it also receives the values of the total it is compared with. |
| `field_headers` | `0` the ranges have no header row, `1` they have one and it is not shown, `2` they have none and headers are generated (**Row Field 1**, **Column Field 1**, **Value 1**), `3` they have one and it is shown. Left out: a header row is assumed when the first cell of `values` is text and the second is a number, and it is shown when there is more than one row field, column field or value column. |
| `total_depth` | `0` no totals, `1` a grand total, `2` a grand total and subtotals for the first field, and so on for more fields; negative numbers put totals first. Left out: a grand total, and subtotals when there are two or more fields. The grand total is labelled **Total**, or **Grand Total** when there are subtotals. |
| `sort_order` | The number of an output column to sort by, counting the fields first and then the value columns; negative for descending. An array sorts by several. Left out: the fields, ascending. A value column sorts each level by its own total. |
| `filter_array` | A column of logical values, one for each row, or one for each row below the header. Rows with `FALSE` are left out. |
| `relative_to` | For a function with two parameters in `PIVOTBY`: `0` column totals (default), `1` row totals, `2` the grand total. In `GROUPBY` the second parameter is always the whole column. |

- Groups are matched without regard to case. Rows whose field cells are all empty are skipped, so a range may extend below the data.
- A combination with no rows gives an empty text in `PIVOTBY`, as do the label cells of total rows.
- Not supported: several functions at once (`HSTACK(SUM, AVERAGE)`), `field_relationship` other than `0`, and `relative_to` `3` and `4` (parent totals). These return `#VALUE!`.
- The results follow Microsoft's documentation of the two functions. They are not checked in Excel, and LibreOffice does not have them.
- In an xlsx file the functions are written as `_xlfn.GROUPBY` and `_xlfn.PIVOTBY`, and a function name passed as an argument as `_xleta.SUM`, which is how Excel stores them. Excel for Microsoft 365 calculates them; older versions and LibreOffice show `#NAME?`.

[`GETPIVOTDATA`](https://docs.birchui.com/spreadsheet/pivot-tables.md#getpivotdata) reads a value from a pivot table.

## Custom functions

Register a JavaScript function under a name and formulas can call it like a built-in one. Use this for calculations the built-in list does not cover, or for values that come from your own code, such as a price list or an exchange rate.

```ts
const sheet = createSpreadsheet(container, {
  functions: {
    NET_OF_TAX: (amount, rate) => Number(amount) / (1 + Number(rate)),
    'REGION.TARGET': {
      impl: (region) => targets[String(region)] ?? { error: '#N/A' },
      args: 'region',
      description: 'Quarterly sales target for a region',
    },
  },
});

sheet.registerFunction('COMMISSION', (sales) => Number(sales) * 0.05, { args: 'sales' });
sheet.setFormula('C2', '=COMMISSION(REGION.TARGET(A2))');
```

`functions` takes a map of names to functions or definitions, or an array of `{ name, impl, ... }` objects. `registerFunction(name, impl, options?)` adds one later and recalculates the cells that call it, `unregisterFunction(name)` removes one (those cells go back to `#NAME?`), and `update({ functions })` replaces the set that came from the option.

**`CustomFunctionOptions`** (interface from `@birchui/spreadsheet`, full reference: https://docs.birchui.com/api/spreadsheet.md)

```ts
interface CustomFunctionOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `args?` | `string` |  |
| `description?` | `string` |  |
| `volatile?` | `boolean` |  |
| `async?` | `boolean` |  |
| `override?` | `boolean` |  |

| Option | Effect |
| --- | --- |
| `args` | The argument list shown in the editor's hint, such as `'amount, [rate]'`. It is documentation only; the number of arguments is not checked. |
| `description` | One line shown in autocomplete and the Insert Function dialog. |
| `volatile` | Recalculate on every change, like `NOW()`. |
| `async` | The function returns a promise. A function that returns a promise without this flag is treated the same way from its first call on. |
| `override` | Allow the name of a built-in function. Without it, registering `SUM` throws. |

### Names

A name uses letters, digits, `.` and `_`, and starts with a letter or `_`. It is not case-sensitive. It cannot look like a cell reference (`A1`, `TAX2026`), and it cannot be `LET`, `LAMBDA`, `TRUE` or `FALSE`. An invalid name makes `registerFunction` throw. An invalid entry in the component's `functions` option logs one warning and is skipped; `createFormulaEngine({ functions })` throws instead. A custom function takes precedence over a defined name or a `LET` variable of the same name.

Functions belong to the spreadsheet or engine they were registered on. Two spreadsheets on a page do not share them, and the module-level `listFunctions()` keeps returning the built-in list. The instance method `listFunctions()` on the component and on the engine includes the custom ones, with `category: 'custom'`.

### Arguments and results

Arguments arrive evaluated:

| In the formula | The function receives |
| --- | --- |
| A number, text, logical value or a single cell | `number`, `string`, `boolean`, or `null` for an empty cell |
| A range such as `B2:D10`, or an array such as `{1,2;3,4}` | A 2D array of those values, rows first |
| An error, such as a cell showing `#DIV/0!` | The error value; test it with `isCellError()` |

A whole-column reference is cut down to the used rows. A union of ranges, such as `(A1:A3,C1:C3)`, gives `#VALUE!` without calling the function.

The return value becomes the cell value. A 2D array [spills](#dynamic-arrays-and-spilling); rows of different lengths are padded with `#N/A`. A `Date` becomes a date serial, `undefined` and `null` become an empty value (shown as 0), and `{ error: '#N/A' }` or an error value you received returns that error. A number that is not finite gives `#NUM!`. Anything else, such as a plain object or a 1D array, gives `#VALUE!`.

If the function throws, the cell shows `#VALUE!` and the error is reported: the component fires its [`error` event](https://docs.birchui.com/spreadsheet/api.md#error-codes) with `code: 'formula'`, the sheet and the cell address, and the engine fires `functionError`. The page keeps working. A function that fails in many cells is reported once per recalculation.

### Async functions

```ts
sheet.registerFunction(
  'FX_RATE',
  async (currency) => {
    const response = await fetch(`/api/rates/${String(currency)}`);
    return (await response.json()).rate;
  },
  { async: true, args: 'currency', description: 'Exchange rate against USD' },
);
```

- While the promise is pending the cell shows `#BUSY!`, and so do formulas that use it. Wrap the call in `IFERROR` to show something else.
- When the promise resolves, the cell takes the value and its dependants recalculate. `recalculated` fires as usual.
- A rejected promise gives `#VALUE!` and is reported like a thrown error.
- Results are cached by function name and argument values. Other cells with the same arguments, and later recalculations, reuse the result without calling the function again. That is also what stops a recalculation from looping.
- To fetch fresh values, call `recalculate()`, or register the function again. A `volatile` async function does not refetch on its own; it reuses the cached result.
- A result that arrives after the cell was overwritten, or after its arguments changed, is not written to the cell.
- `whenCalculated()` resolves once no async result is outstanding.

The cache keeps up to 10,000 results per spreadsheet and drops the oldest when it grows past that. The spreadsheet makes no network calls itself; what an async function does is up to your code.

### In files

Custom functions are code, so they are not stored in the workbook JSON or in an xlsx file. A formula that calls one is saved as written, with the value it had: xlsx export writes `REGION.TARGET(A2)` and the cached value, Excel shows that value and `#NAME?` once it recalculates, and importing the file gives the formula and value back. A cell still showing `#BUSY!` is saved as `#N/A`. A workbook that uses functions you have not registered opens with its cached values in the JSON and shows `#NAME?` in those cells until you register them.

### Limits

- A function gets values, not references. It cannot read other cells, learn which cell called it, or write to the sheet.
- Functions run on the thread that calculates. A slow synchronous function blocks typing; make it `async` or use [worker calculation](https://docs.birchui.com/spreadsheet/worker-calculation.md#custom-functions).
- With `calculation: 'worker'`, functions must also be registered inside the worker, because a function cannot be sent to one. See [Custom functions in a worker](https://docs.birchui.com/spreadsheet/worker-calculation.md#custom-functions).
- Custom functions are not listed in the ribbon's function library menus. They appear in autocomplete, in the argument hint and under Custom in the Insert Function dialog.
- LibreOffice and Excel do not know your functions, and ods and CSV export write values only where those formats do.

## Dynamic arrays and spilling

A formula that returns more than one value spills its results into the cells below and to the right, as in current versions of Excel:

```text
=SEQUENCE(360)
=SORT(FILTER(Orders!A2:F500, Orders!E2:E500 = "Overdue"), 6, -1)
=UNIQUE(Orders!C2:C500)
=XLOOKUP(H2, A2:A500, B2:D500)
```

- The formula lives in the top-left cell, the anchor. The other cells of the spill range show its results.
- When a value sits in the way, including one typed into the spill range, the anchor shows `#SPILL!` until the space is cleared; the results then appear again automatically.
- The spill range resizes as the source data changes.
- Functions that return arrays include `SEQUENCE`, `FILTER`, `SORT`, `SORTBY`, `UNIQUE`, `TRANSPOSE`, `VSTACK`, `HSTACK`, `TAKE`, `DROP`, `CHOOSECOLS`, `TEXTSPLIT`, `RANDARRAY` and `XLOOKUP` with a multi-column result. Arithmetic on ranges, such as `=B2:B13 * 1.2`, spills too.

Refer to a whole spill with the spill range operator, `#`, after the anchor: `=SUM(F2#)`, `=ROWS(Orders!H2#)`. The reference grows and shrinks with the spill. It also works after a defined name that points at one cell (`=MAX(Anchor#)`). On a formula that does not spill it is that one cell, and on a cell without a formula it is `#REF!`. In xlsx files the operator is stored as `_xlfn.ANCHORARRAY(F2)`, as Excel stores it, and read back as `F2#`.

`@` is the implicit intersection operator: `=@A1:A10` takes the value on the formula's own row, and `=@SEQUENCE(3)` takes the first value of an array. In files it is stored as `_xlfn.SINGLE()`.

To reproduce the behaviour of older Excel versions, set `dynamicArrays: false`. Ranges in single-value positions then use implicit intersection: `=A1:A3 * 10` in row 2 uses only `A2`. Functions whose arguments are arrays still receive arrays, as they did in those versions: `=SUMPRODUCT((A1:A3>1)*B1:B3)`, `MMULT`, `TRANSPOSE`, `FREQUENCY`, `LINEST`, `TREND`, `INDEX`, `MATCH`, `LOOKUP` and the statistical functions that take two data sets evaluate their arguments element by element, while `=SUM((A1:A3>1)*B1:B3)` intersects.

## Errors

| Error | Cause |
| --- | --- |
| `#DIV/0!` | Division by zero. |
| `#VALUE!` | An argument has the wrong type, such as text in arithmetic. |
| `#REF!` | A reference points to deleted cells or outside the sheet. |
| `#NAME?` | An unknown function or name, or a syntax the parser does not support. |
| `#N/A` | A lookup found no match, or `NA()` was used. |
| `#NUM!` | A numeric problem, such as `SQRT(-1)` or an `IRR` that does not converge. |
| `#NULL!` | An intersection of ranges that do not overlap. |
| `#SPILL!` | A spill range is blocked. |
| `#CALC!` | A calculation produced no result, such as `FILTER` with no matches, or a `LAMBDA` left uncalled. |
| `#BUSY!` | An [async custom function](#async-functions) has not returned yet. |

Errors propagate through formulas that use them. Catch them with `IFERROR` or `IFNA`, test them with `ISERROR`, `ISNA` and `ERROR.TYPE`, and in code with `isCellError()`:

```ts
import { isCellError } from '@birchui/spreadsheet';

const payment = sheet.getValue('B4');
if (isCellError(payment)) console.warn(`Payment is ${payment.code}`);
```

## Circular references

A formula that depends on itself, directly or through other cells, is a circular reference. The cells involved show 0 and the spreadsheet emits an `error` event with the code `circularReference`, so you can tell the user.

For models that are circular by design, such as interest on an average balance, turn on iterative calculation. The engine then repeats the calculation until values change by less than `maxChange` (0.001 by default), or `maxIterations` (100 by default) is reached:

```ts
createSpreadsheet(container, {
  data: model,
  iterativeCalculation: { maxIterations: 200, maxChange: 0.0001 },
});
```

## Volatile functions

`NOW`, `TODAY`, `RAND`, `RANDBETWEEN`, `RANDARRAY`, `OFFSET` and `INDIRECT` are volatile: they recalculate whenever any value in the workbook changes, and on `recalculate()`. A [custom function](#custom-functions) registered with `volatile: true` behaves the same way. Use them sparingly in large workbooks; prefer `INDEX` over `OFFSET` and direct references over `INDIRECT`.

Pass a `now` function to make `NOW` and `TODAY` deterministic, for example in tests or to show a model as of a fixed date:

```ts
createSpreadsheet(container, { data: model, now: () => new Date(2026, 11, 31) });
```

## Recalculation

The engine keeps a dependency graph, so a change re-evaluates only the cells that depend on it, in dependency order, and stops early when a result does not change. Large ranges such as `SUM(A1:A100000)` are indexed by blocks rather than registered cell by cell. After each recalculation the spreadsheet emits `recalculated` with the number of changed cells and the time it took. `recalculate()` forces a full recalculation. See [Performance](https://docs.birchui.com/spreadsheet/performance.md).

## Dates and times

Dates are serial numbers in the 1900 date system: 1 is 1 January 1900 and 46096 is 15 March 2026, with the time as a fraction of a day. Excel's 1900 leap-year quirk is reproduced, so serials match Excel exactly. `dateToSerial()` and `serialToDate()` convert between `Date` objects and serials, in UTC. A `Date` passed to `setValue()` is stored as a serial.

## Verified against LibreOffice

The formula engine is checked against LibreOffice Calc. A workbook with 1,604 formulas, at least three for each of the 501 functions that `listFunctions()` returns (a typical case, an edge case and an error case), is recalculated by LibreOffice 26.8, and the engine must produce the same values within a relative tolerance of 1e-9 (1e-7 for `BESSELK`, where LibreOffice uses a polynomial approximation).

| | Formulas |
| --- | --- |
| Same result in LibreOffice and here | 1,241 |
| Both return an error, with different error codes | 228 |
| Functions LibreOffice does not calculate (20 functions) | 60 |
| Google Sheets functions that LibreOffice does not have (4 functions) | 13 |
| Logical values, which LibreOffice stores as numbers | 18 |
| Other documented differences | 44 |

Every formula in the last five rows is listed in the test suite with the reason, and, except four formulas whose result Excel does not document, with the value the engine must return:

- **Error codes.** LibreOffice reports most invalid arguments as `Err:502`, which it writes to xlsx as `#VALUE!`, and it has no `#CALC!`. The engine returns the code Excel documents, such as `#NUM!` for `SQRT(-1)` and `#DIV/0!` for `MOD(5,0)`.
- **Functions not in LibreOffice.** `ARRAYTOTEXT`, `BINOM.DIST.RANGE`, `BYCOL`, `BYROW`, `GROUPBY`, `ISOMITTED`, `MAKEARRAY`, `MAP`, `ODDFPRICE`, `ODDFYIELD`, `PERCENTOF`, `PHONETIC`, `PIVOTBY`, `REDUCE`, `REGEXEXTRACT`, `REGEXREPLACE`, `REGEXTEST`, `SCAN` and `VALUETOTEXT` are checked against the values in the Excel documentation only.
- **Google Sheets functions.** `SPLIT`, `COUNTUNIQUE`, `ARRAYFORMULA` and `ARRAY_CONSTRAIN` exist for workbooks that come from Google Sheets. Excel does not have them either and shows `#NAME?` for them in an exported file; their values are checked against Google's documentation.
- **Logical values.** LibreOffice keeps `TRUE` and `FALSE` as 1 and 0, so `COUNT`, `AVERAGE` and the variance functions count them in a range and text functions print `1`. The engine keeps a logical type, as Excel does.
- **Other differences** are cases where LibreOffice departs from what Excel documents: day counts under US 30/360 across February of a leap year (`INTRATE`, `RECEIVED`, `PRICEDISC`), `ACCRINT` ignoring the first interest date, `DURATION` and `MDURATION` with an approximate coupon count, `PRICE` and `ODDLPRICE` with one coupon period left, `PERCENTRANK` rounding instead of truncating, `MODE` returning the smallest of several modes, negative amounts in `DOLLAR`, the sheet separator in `ADDRESS`, and domain checks such as `ATAN2(0,0)`, `MROUND(5,-2)` and `CHAR(0)`.

Building the suite found two defects, both fixed: `NETWORKDAYS.INTL`, `WORKDAY.INTL` and `ISO.CEILING` were written to xlsx with an `_xlfn.` prefix they do not take, so LibreOffice showed `#NAME?`; and `IMSUM`, `IMSUB`, `IMPRODUCT` and `IMDIV` accepted complex numbers with different suffixes, where Excel documents `#VALUE!`.

Agreement with LibreOffice is not agreement with Excel: nothing here is run in Microsoft Excel. Where the two programs are known to differ, the engine follows the Excel documentation. To repeat the check, with LibreOffice (`soffice`) on the `PATH`:

```sh
node packages/spreadsheet/scripts/golden-formulas.mjs
```

It exports the workbook, has LibreOffice recalculate it with recalculation on load forced, rewrites `test/fixtures/formula-golden.json` and runs the comparison. The comparison against the stored values also runs in the normal test suite, without LibreOffice.

## Formula language and locale

Formulas use the en-US syntax that Excel stores in files: commas between arguments, a period as the decimal separator and English function names. Localized syntax, such as semicolons as separators or translated function names, is not accepted.
