HotXLS Docs

Excel Calculation Engine

Overview

HotXLS includes a built-in engine for parsing and calculating formulas; this engine evaluates cell formulas programmatically within your process, eliminating the 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 using the main workbook interface

procedure Calculate;

The engine supports standard mathematical, date, logical, string, and statistical families of functions; it sequentially resolves cell dependencies and follows reference chains to prevent circular references

Contextual Formula Evaluation

TXLSWorksheet and TXLSXWorksheet expose EvaluateFormulaAt to calculate formula text in a selected one-based row and column without writing a temporary cell or changing workbook calculation state

A1 and R1C1 reference styles, local names, structured references, formula dependencies, array roots, typed Excel error values, volatile status, explicit external-reference authorization, cancellation, and stable failure categories share the normal workbook evaluator

CreateFormulaEvaluationTemplate compiles an immutable anchor once and reuses it across target cells; target-row-sensitive A1 structured references are resolved for each target context, and per-call limits bound formula length, syntax-item steps, recursion depth, and generated array bytes

See Contextual formula evaluation for 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 referenced workbook model 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 return #REF!, and external-workbook metadata is unavailable and returns #REF!

When the reference is omitted, HotXLS uses the formula cell or the target supplied to EvaluateFormulaAt; this headless convention does not depend on an Excel window's active selection

info_typeResult and boundary
address, row, colAbsolute A1 address and numeric one-based coordinates
contents, typeThe original value type or spreadsheet error, with zero for blank contents; type returns b for blank, l for text, and v for other values and errors
filenameSaved full path in path[workbook]worksheet form, using the referenced worksheet; an unsaved workbook returns an empty string
formatA documented English format category from the stored base number format; unsupported locale-specific or unclassified custom masks produce an unsupported-function status during contextual evaluation
color, parenthesesNumeric flags inspecting an explicit color in the negative format section and paired parentheses in the positive format section; quoted and escaped literals are distinguished from format directives
prefixFor text constants, general or left alignment returns an apostrophe, centered alignment a caret, right alignment a double quote, and fill alignment a backslash; numeric cells and formulas returning text have an empty prefix
protectNumeric one or zero from the cell's effective base Locked state, including inherited defaults; this flag does not indicate whether worksheet protection is enabled
widthA one-row, two-column array containing character width rounded to the nearest integer and a Boolean indicating whether the default width applies; a hidden column reports width zero

Base formatting includes stored cell and applicable default formatting; conditional-format and table appearance rules are 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 use G

English date or time familyCode
m/d/yyD4
d-mmm-yyD1
d-mmmD2
mmm-yyD3
mm/ddD5
h:mm AM/PM, h:mm:ss AM/PMD7, D6
h:mm, h:mm:ssD9, D8

The format code appends - for a negative-section color and () for positive-section parentheses; date classifications follow the published en-US categories and may differ from the codes produced by a particular localized Excel build

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 participate in volatile recalculation, while format scanning and width arrays honor 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 changing 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 uses character units

TXLSGetCalculationMode returns the workbook's Manual or Automatic mode; callbacks are borrowed, must outlive the calculator, and must read metadata without mutating or recalculating the target workbook

Array Operators

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 return #VALUE!

Errors are retained in their individual result cells, so one division by zero or invalid element does not discard 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 contain #N/A; when a selector is an array, zero selects the first member, while scalar-only zero selectors retain whole-row or whole-column extraction

Array-selector results preserve selected value types and errors, honor 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 retain 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, while MUNIT returns a compact two-dimensional Double identity matrix

FormulaArrayMemoryLimit defaults to 64 MiB and bounds generated matrix payloads; MUNIT also validates the remaining worksheet spill area instead of 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 works when the target formula returns an error or uses an unsupported function

A rectangular reference returns 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 return #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 return #N/A

XLSX retains formula text from its model and writes _xlfn.FORMULATEXT on save; Classic XLS inspects its existing formula tokens using the same displayed text as its Formula property and stores the function in BIFF8 cells through 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 honor 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 identify the required row, column, or selected page members

The pivot reference can be a cell, range, or 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 can 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 must 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 materialization; 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, releases 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 instead of 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 while 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 supply query totals

GETPIVOTDATA uses its native BIFF function identity for Classic XLS storage and participates 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 when its cached result is an error or an empty string

A rectangular range returns a same-shaped Boolean array; shared-formula and classic or XLSX array-formula members return true, while only the anchor of a dynamic spill is 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 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 toward zero and converts valid Unicode scalar values to UTF-16, including surrogate-pair output for supplementary planes and all private-use ranges

UNICODE returns 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, returns #VALUE!; XLSX saves it as _xlfn.UNICODE and restores the bare name when reopened

Zero and out-of-range inputs return #VALUE!, while isolated surrogate code points and Unicode noncharacters return #N/A; range and generated-array inputs preserve these errors per element

BAHTTEXT converts finite numbers to Thai baht and satang text, rounds midpoint values away from zero at two decimal places, retains 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 uses its standard function identity and remains bare in XLS and XLSX formulas

USDOLLAR and YEN format an amount 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 gives one dollar and one cent even though the stored double is slightly below it, and a negative decimals argument rounds to tens or hundreds

DOLLAR shares that rounding and keeps its minus sign before the symbol, so the only 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 are irrevocably fixed by Council Regulation 2866/98 and the regulations that added the later member states, converting through the euro and rounding only the final amount

Unless full_precision is true, the result takes the target currency's own number of decimals, so one euro is 1.96 marks and one mark is 990 lire; with full precision the unrounded conversion is returned

Currency codes are matched case-insensitively and an unknown code returns #VALUE!; a file that carries EUROCONVERT is read and written with the bare function name, and a spreadsheet application evaluates it when 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, while 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 participate in step and memory limits

See calculation and conversion fidelity for selector ordering, negative indices, empty-result errors, and lookup boundaries

Regression and Prediction

LINEST and LOGEST accept one or more predictor columns or rows and return 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, regression sum of squares, and residual sum of squares

TREND and GROWTH use the same multivariable model and preserve the row or column shape of the supplied new predictor values

Classic XLS Dependency Recalculation

TXLSWorkbook.Recalculate builds a formula dependency graph on its first call and evaluates formulas in precedent-first order rather than 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 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, while UseFullPrecision=False applies the displayed number precision to cached results and their downstream calculations

Defined-Name Dependencies

Incremental calculation follows workbook-scoped and worksheet-scoped names through nested formulas and multi-area references

Acyclic name formulas contribute their exact cell dependencies, while 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 calculated output cells, while formulas and trial values use the surrounding cells in the same layout as Excel

  • Column-input table — leave ARowInputCell empty, put a source formula above each result column, and put trial values to the left of the result rows
  • Row-input table — leave AColumnInputCell empty, put a source formula to the left of each result row, and put 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, row-input trial values above the results, and 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 that reach B1 indirectly through other formula cells are recalculated correctly

AddDataTable returns nil for an invalid range, an invalid input reference, or when 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]) use the bundled PCRE2 10.49 backend on Delphi and C++Builder Windows builds and on native FPC Linux x64 and macOS ARM64 builds

Patterns use 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 behavior

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 returns an empty string

REGEXREPLACE supports numbered capture references such as $2, $1; occurrence 0 replaces every match, a positive occurrence selects a match from the beginning, and a negative occurrence selects one from the end; a missing selected occurrence leaves the text unchanged

Empty matches are handled with 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 occupy 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 return #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 participate 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 require 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 explicitly and do not 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 returns #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 a 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]) summarizes 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]) summarizes 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 do not create, refresh, or modify a PivotTable, source cells, formula caches, or worksheet layout

Each field and values argument must have the same number of rows; multiple field columns form a hierarchy, and multiple values columns create separate measures; a Boolean filter must be a single column with 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 determines 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, while vertical results repeat each group in function-vector order

Each callback receives a column vector of contributing values and must 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 retain their blank-input semantics instead of 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 returns #DIV/0!; GROUPBY supplies all selected records as the second population, while 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 shows 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 while preserving the first spelling, numeric values and dates share their numeric identity, Boolean and text keys remain distinct from numbers, and blank keys remain distinct from empty text keys

Positive total depths place totals after their groups and negative depths place them before their groups; depth 1 includes the grand total, deeper depths add successive parent subtotals, and omitted depth includes every available parent level; GROUPBY's field_relationship=1 sorts complete tuples as a table and permits 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 only; 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 publishes 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 while 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 behavior 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 presented as universal native-build equivalence

User-Defined Functions

Extend the formula engine with custom business logic; register your own functions using the events below

Dangerous external and macro-style names are denied before arguments or handlers run unless the workbook or individual contextual evaluation explicitly enables AllowUnsafeFormulaCallbacks