Excel Calculation Engine
Overview
HotXLS includes a built-in engine for parsing and calculating formulas; this engine evaluates cell formulas programmatically within your process, so there is no need to call Excel or external OLE controllers to resolve calculated workbook values
Calculation Execution
Before saving or exporting, trigger a full recalculation of the workbook through the main workbook interface
procedure Calculate;
The engine supports standard mathematical, date, logical, string, and statistical families of functions; it resolves cell dependencies in sequence and follows reference chains to prevent circular references
Contextual Formula Evaluation
TXLSWorksheet and TXLSXWorksheet expose EvaluateFormulaAt, which calculates formula text at a chosen one-based row and column without writing a temporary cell or disturbing the workbook's calculation state
A1 and R1C1 reference styles, local names, structured references, formula dependencies, array roots, typed Excel error values, volatile status, explicit external-reference authorisation, cancellation and stable failure categories all go through the normal workbook evaluator
CreateFormulaEvaluationTemplate compiles an immutable anchor once and reuses it across the target cells; target-row-sensitive A1 structured references are resolved for each target context, whilst per-call limits bound formula length, syntax-item steps, recursion depth and generated array bytes
See Contextual formula evaluation for the result types, default budgets, lifetime rules and Delphi or C++Builder examples
CELL and INFO Metadata
Classic XLS and XLSX calculate CELL(info_type, [reference]) against the workbook model being referenced without creating empty cells, changing selections, or writing formula caches during read-only evaluation
A rectangular reference uses its top-left cell and a single worksheet; defined names and supported reference-producing expressions retain their reference context, invalid references give #REF!, and external-workbook metadata is unavailable and returns #REF!
When the reference is omitted, HotXLS uses the formula cell or the target handed to EvaluateFormulaAt; this headless convention does not rely on an Excel window's active selection
| info_type | Result and boundary |
|---|---|
address, row, col | Absolute A1 address and numeric one-based coordinates |
contents, type | The original value type or spreadsheet error, with zero for blank contents; the type returns b for blank, l for text, and v for other values and errors |
filename | Saved full path in path[workbook]worksheet form, using the referenced worksheet; an unsaved workbook gives an empty string |
format | A documented English format category taken from the stored base number format; unsupported locale-specific or unclassified custom masks produce an unsupported-function status during contextual evaluation |
color, parentheses | Numeric flags inspecting an explicit colour in the negative format section and paired parentheses in the positive format section; quoted and escaped literals are told apart from format directives |
prefix | For text constants, general or left alignment returns an apostrophe, centred alignment a caret, right alignment a double quote, and fill alignment a backslash; numeric cells and formulas returning text have an empty prefix |
protect | Numeric one or zero from the cell's effective base Locked state, including inherited defaults; this flag does not show whether worksheet protection is enabled |
width | A one-row, two-column array containing character width rounded to the nearest integer and a Boolean saying whether the default width applies; a hidden column reports width zero |
Base formatting covers stored cell and applicable default formatting; conditional-format and table appearance rules sit outside this metadata contract
Supported numeric format categories are F<n> for fixed-point, ,<n> for grouped numbers, C<n> for dollar currency, P<n> for percentages, and S<n> for scientific notation, where n is the fractional placeholder count; General, text, fraction, and elapsed-time masks all use G
| English date or time family | Code |
|---|---|
m/d/yy | D4 |
d-mmm-yy | D1 |
d-mmm | D2 |
mmm-yy | D3 |
mm/dd | D5 |
h:mm AM/PM, h:mm:ss AM/PM | D7, D6 |
h:mm, h:mm:ss | D9, D8 |
The format code appends - for a negative-section colour and () for positive-section parentheses; date classifications follow the published en-US categories and can differ from the codes a particular localised Excel build produces
INFO("recalc") reads the workbook calculation mode and returns Manual or Automatic, with automatic-except-tables included in Automatic; INFO("system") returns the Windows identifier pcdos and INFO("release") identifies this evaluator as HotXLS
Excel application state is unavailable in a headless workbook: directory, origin, numfile, osversion, memavail, memused, and totmem return #N/A; unknown CELL or INFO information types return #VALUE!
Metadata functions take part in volatile recalculation, whilst format scanning and width arrays honour contextual cancellation, evaluation-step limits, and array-memory limits
Custom TXLSCalculator integrations can assign OnGetCellInfo: TXLSGetCellInfo and OnGetCalculationMode: TXLSGetCalculationMode; workbook facades install these callbacks for normal, read-only, and supported parallel evaluation, without altering the calculator constructor
TXLSGetCellInfo receives a one-based SheetIndex and zero-based Row and Col, and fills TXLSCellInfoSnapshot with FileName, SheetName, NumberFormat, HorizontalAlignment, Locked, ColumnWidth, and DefaultColumnWidth; it returns lxOk or an evaluator error code; the alignment uses the existing numeric workbook alignment codes and width is expressed in character units
TXLSGetCalculationMode returns the workbook's Manual or Automatic mode; callbacks are borrowed, must outlive the calculator, and must read metadata without mutating the target workbook or triggering recalculation
Array Operators
The arithmetic, comparison, concatenation, unary negation and percent operators accept calculated arrays as well as scalar values
A scalar broadcasts across every element, and a one-row or one-column array broadcasts across a compatible dimension; incompatible shapes yield #VALUE!
Errors are kept in their individual result cells, so a single division by zero or invalid element does not throw away the values calculated for the remaining cells
INDEX accepts selector arrays over reference and calculated sources: opposing orientations produce a cross-product, matching orientations pair selections, and unmatched positions in unequal shapes carry #N/A; when a selector is an array, zero selects the first member, whilst scalar-only zero selectors keep whole-row or whole-column extraction
Array-selector results preserve selected value types and errors, honour matrix memory and evaluation-step limits, and compose with FILTER, SORT, UNIQUE and LET; row, column and area selectors can broadcast together, and supported scalar reference results keep their identity through defined names, LET and scalar CHOOSE; see INDEX area selection for the calculated-source fourth argument and reference-union boundaries
COMBINA and PERMUTATIONA share scalar and broadcast-array semantics, with truncated non-negative integer arguments and checked overflow, whilst MUNIT returns a compact two-dimensional Double identity matrix
FormulaArrayMemoryLimit defaults to 64 MiB and bounds the generated matrix payloads; MUNIT also validates the remaining worksheet spill area rather than imposing a fixed dimension ceiling
Formula Text Inspection
FORMULATEXT(reference) returns the stored formula with its leading equals sign without evaluating the referenced formula or altering its cached value; text inspection still works when the target formula returns an error or calls an unsupported function
A rectangular reference gives a same-shaped array of formula strings and per-cell errors, matching modern array evaluation; explicit @ intersection can select a scalar result
Blank cells, constants, formulas longer than 8192 characters, protected cells whose formulas are hidden, and external-workbook formula metadata come back as #N/A; invalid references retain #REF! and non-reference inputs return #VALUE!
Classic array formulas retain their {=...} display form for both anchors and member cells; dynamic spill children are values rather than formula owners and give #N/A
XLSX retains formula text from its model and writes _xlfn.FORMULATEXT on save; Classic XLS inspects its existing formula tokens against the same displayed text its Formula property shows and stores the function in BIFF8 cells via the hidden _xlfn.FORMULATEXT name Excel uses
Standalone contextual evaluation supports both engines, and XLSX cells can inspect their own stored formula text without creating a circular dependency; formula edits invalidate dependent metadata queries and generated text arrays honour evaluation-step and memory limits
Visible Pivot Data
GETPIVOTDATA(data_field, pivot_table, [field, item], ...) retrieves a visible aggregate from a local worksheet PivotTable in Classic XLS or XLSX; up to 126 field/item pairs pin down the required row, column, or selected page members
The pivot reference can be a cell, a range, or a defined name intersecting the table; if it intersects several tables, the most recently added table supplies the result, and external or non-pivot references return #REF!
Data fields match their displayed caption or their source field name without regard to case; field/item pairs may appear in any order, numeric and date members use their typed numeric identity, and compatible argument arrays broadcast with errors preserved per element
A requested subtotal or grand total has to be visible in the table's configured layout; requesting an inner row member without its outer members, a hidden or absent member, a disabled total, or a page item outside the selected report filter returns #REF!
The query evaluates an independent table/cache snapshot using the same filtering, subtotal, aggregation, calculated-member, and ShowDataAs machinery as Pivot materialisation; it reads the existing bound cache without refreshing the worksheet source or rewriting the report cells
Query preflight accounts for the detached model and string payloads before cloning, and aggregation checks work and memory limits before large accumulator allocations; cancellation, including cancellation raised by a record filter, frees the snapshot and leaves the live model unchanged
Incomplete or external caches, grouped cache fields, unsupported calculation expressions, and aggregates that cannot reproduce cached source errors report an unsupported-function status rather than returning an inferred total; calculated result errors that the Pivot model can represent remain typed spreadsheet errors
Imported XLSX caches require matching definition and record counts, complete record widths, and valid typed or shared-item values; unknown values, extra values, and missing or unavailable shared-item references disable query execution whilst preserved raw parts remain available for save
Imported BIFF caches bind inline value records to the current cache row and field; record-validity metadata follows the format's newer cache-extension, view-tag, and SXDB precedence, and invalid cached records cannot provide query totals
GETPIVOTDATA keeps its native BIFF function identity for Classic XLS storage and takes part in volatile recalculation so changes to typed Pivot view settings can be reflected without editing the query formula
Formula Presence Inspection
ISFORMULA(reference) inspects formula ownership without calculating the referenced cell, so a formula remains detectable even when its cached result is an error or an empty string
A rectangular range returns a same-shaped Boolean array; shared-formula members and classic or XLSX array-formula members return true, whilst only the anchor of a dynamic spill counts as a formula cell
Direct values and scalar defined names return #VALUE!, invalid references preserve #REF!, and generated Boolean arrays are bounded by FormulaArrayMemoryLimit
XLSX writes _xlfn.ISFORMULA and restores the bare name on open, ODS uses the standard of:=ISFORMULA syntax, and Classic XLS stores it through the hidden _xlfn.ISFORMULA name Excel uses in BIFF8
Modern Text Functions
UNICHAR truncates numeric inputs towards zero and converts valid Unicode scalar values to UTF-16, including surrogate-pair output for supplementary planes and all private-use ranges
UNICODE gives back the code point of the first character of a text and reads a surrogate pair as one character; an empty text, or a high surrogate without its partner, yields #VALUE!; XLSX saves it as _xlfn.UNICODE and restores the bare name when reopened
Zero and out-of-range inputs return #VALUE!, whilst isolated surrogate code points and Unicode noncharacters return #N/A; range and generated-array inputs preserve these errors per element
BAHTTEXT converts finite numbers into Thai baht and satang text, rounds midpoint values away from zero at two decimal places, keeps a negative sign when the rounded magnitude becomes zero, and expands scientific notation without narrowing through an integer type
XLSX saves UNICHAR as _xlfn.UNICHAR and restores the bare name when reopened; BAHTTEXT keeps its standard function identity and stays bare in XLS and XLSX formulas
USDOLLAR and YEN lay an amount out as currency text with the symbol, grouped thousands and a negative amount in parentheses, rounding through the value's 15-significant-digit decimal form: 1.005 yields one dollar and one cent even though the stored double sits slightly below it, and a negative decimals argument rounds to tens or hundreds
DOLLAR shares that rounding and keeps its minus sign in front of the symbol, so the sole difference from USDOLLAR is the negative form
Euro Conversion
EUROCONVERT(amount, source, target [, full_precision]) converts between the euro and the nineteen currencies whose rates were irrevocably fixed by Council Regulation 2866/98 and the regulations that brought in the later member states, going through the euro and rounding only the final amount
Unless full_precision is true, the result takes the target currency's own decimal count, so one euro is 1.96 marks and one mark is 990 lire; with full precision the unrounded conversion comes back
Currency codes are matched case-insensitively and an unknown code returns #VALUE!; a file that carries EUROCONVERT is read and written under the bare function name, and a spreadsheet application evaluates it whenever its own euro add-in is available
Calculated-array Composition
Calculated inputs and constants compose with TRANSPOSE, MMULT, MDETERM, MINVERSE, CHOOSECOLS, CHOOSEROWS, and the stack, take, drop, flatten, wrap, and expand families
XLOOKUP, XMATCH, and MATCH accept calculated key vectors and array-valued lookup requests; scalar XLOOKUP returns complete matching slices, whilst array requests preserve their own shape and select the first returned component
Typed values and errors survive composition, with strict numeric matrix inputs and explicit shape validation; matrix work, lookup scans, copying, and padding take part in step and memory limits
See calculation and conversion fidelity for selector ordering, negative indices, empty-result errors, and lookup boundary conditions
Regression and Prediction
LINEST and LOGEST accept one or more predictor columns or rows and return the coefficients in Excel order followed by the optional intercept
When the statistics argument is true, both functions return the complete five-row result, containing coefficient errors, fit statistics, the F statistic, degrees of freedom, the regression sum of squares and the residual sum of squares
TREND and GROWTH use the same multivariable model and preserve the row or column shape of the new predictor values you supply
Classic XLS Dependency Recalculation
TXLSWorkbook.Recalculate builds a formula dependency graph on its first call and evaluates formulas in precedent-first order instead of physical cell order
Replacing one formula's text on a cell the graph already knows updates that node in place: its new ranges join the pool, only it and its dependents recalculate, and the twenty-thousand-formula rebuild is skipped - a five-edit sequence over such a workbook costs about 3 ms per edit instead of 112 ms. Adding a formula cell appends its node and removing one leaves a dead entry through which the formulas that read the cell are dirtied, so neither rebuilds either; editing before the graph exists or replacing a formula with a value still does, and the ranges a replaced formula no longer names stay in the pool as dead entries that can only over-dirty the node
Later calls reuse the graph and recalculate only the transitive dependents of changed values plus volatile formulas; formula edits, names, worksheet structure and reference rewrites invalidate and rebuild the graph safely
Circular references use the classic workbook EnableIteration, MaxIterations and MaxIterationChange settings, whilst UseFullPrecision=False applies the displayed number precision to cached results and to their downstream calculations
Defined-Name Dependencies
Incremental calculation tracks workbook-scoped and worksheet-scoped names through nested formulas and multi-area references
Acyclic name formulas contribute their exact cell dependencies, whilst recursive name cycles fall back safely to volatile recalculation
What-If Data Tables
Both classic XLS and modern XLSX worksheets can create, calculate, read, write, copy and structurally adjust one-variable or two-variable What-If data tables
function AddDataTable( const AResultRange, ARowInputCell, AColumnInputCell: WideString ): TXLSDataTable;
The result range contains only the calculated output cells, whilst formulas and trial values use the surrounding cells in the same layout as Excel
- Column-input table — leave
ARowInputCellempty, put a source formula above each result column, and put the trial values to the left of the result rows - Row-input table — leave
AColumnInputCellempty, put a source formula to the left of each result row, and put the trial values above the result columns - Two-variable table — supply both input cells, put the source formula above and to the left of the result range, the row-input trial values above the results, and the column-input trial values to the left
Sheet.Range['B1', 'B1'].Value := 0;
Sheet.Range['D1', 'D1'].Formula := '=B1*2+1';
Sheet.Range['C2', 'C2'].Value := 1;
Sheet.Range['C3', 'C3'].Value := 2;
Sheet.Range['C4', 'C4'].Value := 3;
Table := Sheet.AddDataTable('D2:D4', '', 'B1');
Workbook.Recalculate;
This column-input example calculates 3, 5 and 7 in D2:D4; each trial value is applied through an isolated calculation context, so formulas reaching B1 indirectly through other formula cells are recalculated correctly
AddDataTable returns nil when the range is invalid, the input reference is invalid, or both input references are empty; the worksheet DataTables collection exposes the resulting definition and its deleted-input flags
Deleting a referenced input cell preserves the table definition and returns #REF! for its outputs, matching the stored workbook semantics
Direct backend users can consult the regular expression backend API for UTF-16 offsets, status values and callback accounting
Regular Expression Formulas
REGEXTEST(text, pattern, [case_sensitivity]), REGEXEXTRACT(text, pattern, [return_mode], [case_sensitivity]), and REGEXREPLACE(text, pattern, replacement, [occurrence], [case_sensitivity]) rely on the bundled PCRE2 10.49 backend on Delphi and C++Builder Windows builds and on native FPC Linux x64 and macOS ARM64 builds
Patterns take UTF-16 input with PCRE2 UTF mode and case-sensitive matching by default; pass 1 for case-insensitive matching or use PCRE2 inline options such as (?i) and (*UCP) for explicit pattern behaviour
REGEXEXTRACT returns text: mode 0 returns the first complete match, mode 1 spills all complete matches vertically, and mode 2 spills the first match's numbered capture groups horizontally; an unmatched optional group gives an empty string
REGEXREPLACE supports numbered capture references such as $2, $1; occurrence 0 replaces every match, a positive occurrence takes a match from the beginning, and a negative occurrence takes one from the end; a missing selected occurrence leaves the text unchanged
Empty matches follow the PCRE2 global-match rule: retry a nonempty anchored match at the same position before advancing one Unicode scalar value, including a surrogate pair
REGEXTEST, REGEXREPLACE, and mode 0 of REGEXEXTRACT broadcast compatible scalar, row, column, and rectangular operands; modes 1 and 2 require a single broadcast result because vectors of variable lengths cannot fit inside a rectangular formula result
No extraction match returns #N/A; malformed patterns, invalid UTF-16 input, invalid mode or case selectors, and invalid capture references yield #VALUE!; unsupported vector nesting and unavailable backends report xlfeUnsupportedFunction through contextual evaluation without invoking user-function handlers
PCRE2 allocation, output buffers, extraction vectors, and automatic matching callouts take part in the current calculation context's memory, work, and cancellation controls; a backend match or depth limit reports xlfeResourceLimit and never returns a partial result
Native FPC Linux x64 and macOS ARM64 builds need the pinned static object produced by sh Lib/thirdparty/build-pcre2-unix.sh; they use the same UTF-16 backend, allocator budgets, work callouts, and cancellation controls as Windows; other FPC targets report an unavailable backend up front and never substitute the different URegExpr dialect
OOXML stores these names with the _xlfn. prefix; the BIFF8 engine stores them through hidden _xlfn. names as Excel does, and an Excel version without these functions shows the prefix and answers #NAME?
The function signatures and documented examples follow Microsoft's REGEXTEST, REGEXEXTRACT, and REGEXREPLACE pages; the installed Excel build used for local validation does not expose these Microsoft 365 functions, so edge cases follow the stated PCRE2 and array contracts rather than any claim of universal Excel build equivalence
GROUPBY, PIVOTBY, and PERCENTOF
GROUPBY(row_fields, values, function, [field_headers], [total_depth], [sort_order], [filter_array], [field_relationship]) summarises rows by one or more key fields; 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]) summarises the same records along two axes
Both functions operate on arrays or local worksheet ranges through the current calculation context; they build detached grouping indexes and never create, refresh, or modify a PivotTable, source cells, formula caches, or worksheet layout
Each field and values argument must have the same row count; multiple field columns form a hierarchy, and multiple values columns create separate measures; a Boolean filter must be a single column carrying the original row count, including an input header row when present; no selected records returns #CALC!
The aggregation argument accepts a one- or two-parameter LAMBDA, a bare built-in such as SUM, AVERAGE, COUNT, or PERCENTOF, or a horizontal or vertical vector produced by HSTACK or VSTACK; the vector orientation decides the output orientation, and lexical LET/LAMBDA bindings shadow a built-in of the same name; horizontal results follow the values-column order with the function vector inside each measure, whilst vertical results repeat each group in function-vector order
Each callback receives a column vector of contributing values and has to return one scalar; a two-parameter callback also receives a column vector of the denominator population; arrays or another closure returned by a callback produce #CALC!; empty intersections pass a one-cell blank vector, so reducers keep their blank-input semantics rather than receiving an invented numeric zero
PERCENTOF(data_subset, data_all) uses the existing SUM semantics for both operands and divides the first sum by the second; a zero denominator yields #DIV/0!; GROUPBY supplies all selected records as the second population, whilst PIVOTBY supports relative_to values 0 for column totals, 1 for row totals, 2 for grand totals, 3 for parent column totals, and 4 for parent row totals
field_headers values are 0 for data without headers, 1 for input headers omitted from output, 2 for generated output headers, and 3 for input headers shown in output; automatic detection treats a text first value followed by a numeric second value as a header and displays field headers for multiple field levels
Generated labels use Row field 1, Row field 2, and Value 1, Value 2; total labels use Total; key text groups case-insensitively whilst preserving the first spelling, numeric values and dates share their numeric identity, Boolean and text keys stay distinct from numbers, and blank keys remain distinct from empty text keys
Positive total depths put totals after their groups and negative depths put them before their groups; depth 1 includes the grand total, deeper depths add successive parent subtotals, and an omitted depth includes every available parent level; GROUPBY's field_relationship=1 sorts complete tuples as a table and allows grand totals without hierarchical subtotals
Sort selectors number the field columns followed by the value columns, with negative selectors reversing the order; vectors sort by fields alone; sorting by an aggregated value requires a single aggregation function and otherwise returns xlfeUnsupportedFunction because the selector does not identify which function result to use
Grouping indexes, member lists, callback vectors, output strings, and rectangular output storage share the current evaluation work, memory, and cancellation controls; excessively deep field hierarchies return a resource-limit status, and cancellation or a resource limit never exposes a partial result
XLSX stores future-function prefixes, eta-lambda prefixes, and lexical parameter prefixes and recalculates them after reload; Classic XLS supports contextual evaluation whilst retaining its existing rejection of future-function storage in BIFF8 cells; quoted text and structured-reference labels keep literal prefix strings unchanged
The signatures and documented behaviour follow Microsoft's GROUPBY, PIVOTBY, and PERCENTOF pages; the installed Excel build does not expose these functions, so generated label spelling, typed-key edge cases, and empty-intersection callback representation follow the explicit HotXLS contract above and are not offered as universal native-build equivalence
User-Defined Functions
Extend the formula engine with your own business logic; register custom functions using the events below
Dangerous external and macro-style names are denied before any arguments or handlers run, unless the workbook or an individual contextual evaluation explicitly enables AllowUnsafeFormulaCallbacks
- OnUserFunction event — Handle basic user-defined functions
- OnUserFunctionEx event — Resolve complex functions with cell range parameters
- User function callback — Signature requirements for external handlers