Native calculated Pivot fields and cache-owned items
Calculate from context sums
For a local calculated cache field, the native preview first sums every referenced database field in the requested leaf, subtotal or grand-total context and only then evaluates the formula; dependencies may stay absent from the displayed data fields
For instance, two records with Amount/Units values of 10/1 and 30/9 give a native calculated field result of 40/10 = 4, and a grand total evaluates its own dependency sums rather than adding up the displayed ratios
Calculated items evaluate member references in each complete leaf context, the other row and column axes included; subtotals and grand totals take in the resulting member contributions, so a ratio item can contribute a sum of its leaf ratios
A manually hidden member stays available when another calculated item references it, whilst its own contribution sits outside the displayed totals; with A=40 and B=60, hiding A still leaves Combined=A+B at 100 and keeps Combined in the visible grand total
Where calculated fields and items coexist, item contributions first update their referenced database-field sums, and the calculated field then evaluates those updated context sums
Calculated items may belong to several ungrouped fields; the retained cache definition order decides which field formula writes an intersection last, so shifting a definition can change both that intersection and the displayed totals
An unresolved calculated-member dependency evaluates at the moment it is referenced, a dependency defined later in that order included; a member already calculated in an earlier step keeps its current intersection value when another formula references it
Native field sums ignore Boolean and text source values, keep numeric and date values and propagate typed source errors; lazy IF and IFERROR can deal with an error without evaluating an unused branch
Qualified calculation categories
Positive native execution spans calculated items beyond SUM, represented grouped calculation combinations and added mathematical expression forms, with the separate profiles below laying down supported operands, identities, layouts and lifecycle behaviour
These categories imply nothing about every aggregation, grouping, axis, subtotal or display combination; finite numerical precision, subnormal materialization, MOD boundaries and unsupported ownership keep their documented limits, with raw preservation and refused execution assessed separately
COUNT, COUNTNUMS and PRODUCT calculated items
Ordinary cache-owned native calculated items also take COUNT, COUNTNUMS and PRODUCT in a finite single-row-axis profile, using the selected aggregation to finalize each physical member operand ahead of evaluating its formula
COUNT and COUNTNUMS derived items keep their actual numeric formula result, fractions included; their report totals add up finalized member contributions, whilst PRODUCT multiplies them
With A=[2,3,"note"] and B=[5,2], a calculated A/B evaluates to 1.5 for COUNT and 1 for COUNTNUMS; the qualified four-member report totals are 9.5 and 8 respectively, not counting the derived item as one source row
For numeric A=[2,3,4] and B=[5,2], PRODUCT evaluates A/B as 24/10=2.4 and the qualified report grand total as 576; explicitly refreshing the source after changing 4 into 8 yields 4.8 and grand total 2304
The profile demands one ordinary row field, no columns, grouping, page fields, active filters, native calculated-field plan or table-level calculated members, normal display and automatic or disabled subtotals
COUNT and COUNTNUMS cope with finite nonnegative numbers, missing values and nonempty text; COUNT tallies text whilst COUNTNUMS skips it and insists on at least one numeric source value per ordinary member; PRODUCT takes finite nonnegative numeric source values only
Every member needs a qualified selected metric; Boolean, error, date, empty-string, unsupported mixed PRODUCT sources, negative or nonfinite operands/results, empty metrics and expression errors refuse ahead of output
Public formula edits, explicit source refresh, repeated materialization, detached value queries and save/reopen preserve the retained aggregation and formula identity; unknown, foreign or duplicate cache owners stay unsupported and keep their raw definitions when saved
The final-source checks cover the three native aggregation classes and independent formula/source edits, with five actual Excel opened/refreshed output representatives; budgets keep zero-writer refusal and leave the target as it was
MAX and MIN calculated-item measures
Ordinary non-OLAP native calculated items back MAX and MIN measures alongside SUM in the qualified ungrouped profile, a second source axis and mixed extrema and SUM measures included
Each referenced member is finalized with the current measure aggregation before its formula gets evaluated; the resulting calculated member feeds native totals through that same aggregation
An empty ordinary member may stay blank in the report whilst feeding zero to a referenced calculated-item expression; a text-only member supplies zero for MAX and MIN
MAX and MIN call for normal display, ungrouped cache fields and automatic or disabled subtotals; the admission scan charges the query budget once per preview before scanning the cache and view
Calculated data fields still insist on SUM, and their dependency sums keep the existing behaviour; COUNT, COUNTNUMS and PRODUCT calculated items use the separate finite profile above, whilst the MAX/MIN profile adds no grouping, custom subtotals, display transformations or expression forms
Source edits, cache refresh, calculated-item formula edits, selected and total queries, plus repeated materialization after save and reopen, are qualified against independent native grids
The native comparisons use matching explicit English grand-total captions; localized and other custom grand-total caption fidelity remains its own qualification
Calculated items under discrete manual parent groups
Ordinary SUM calculated items can hang on to their original string database-member identities whilst that source field takes part in supported discrete manual parent groups
Target and operand evaluation swap out the source member and all linked ancestor-group identities together, so a referenced member may sit in a different manual group from the calculated target
The qualified profile takes in disabled subtotals, a row group, a column group with no row field and two-axis reports in both orientations, together with source edits, cache refresh, formula edits, native materialization and repeated save/reopen
A single-measure column-only report leaves its top-left cell blank when no row field exists and keeps the measure caption on the data row; ordinary SUM/MAX/MIN column controls share that correction
New or edited grouped calculated-item formulas bind supported member leaves and serialize previously unqualified leaves with explicit field identity; the live Formula text, operators, whitespace and already qualified tokens stay untouched
Saved formula text may depart from the live edited text; unchanged imported formulas, unknown preserved expressions included, and ungrouped formula output keep their existing serialization behaviour
The formatter uses the existing expression grammar, caps rewritten formulas at 32767 UTF-16 code units and the formula set at 1048576 units, and turns away unknown or ambiguous edited bindings before replacing its destination list
Supported linked parents come before their source on the same axis; parent/source page fields, hidden members, advanced filters, transformed measures and range/date transformations of the calculated-item source stay outside this profile
Grouped MAX/MIN items, additional aggregations, custom or localized subtotal caption fidelity, topology or caption edits without formula changes and broader expression/layout combinations call for separate qualification
New retained parent maps and key adjustments join the existing query budget and storage bounds; the pre-existing grouping planner keeps its own allocation and caption-scan behaviour, so this increment promises no budget callbacks before every grouping operation
Native acceptance opens and explicitly refreshes all fifteen final grouped and ordinary column-control outputs; special-character formatter checks establish parser roundtrip structure without claiming native acceptance for each caption character
Native mathematical expressions
INT, TRUNC, SIGN, LN, LOG, EXP and MOD widen the existing bounded calculated-field and calculated-item expression grammar inside its supported source, grouping and aggregation profiles
INT, SIGN, LN and EXP take a single argument; TRUNC and LOG accept one or two, with zero decimal places and base ten as the respective defaults
INT floors toward negative infinity at the calculator's existing fifteen-digit near-integer resolution; TRUNC heads toward zero, truncates its digits argument and sticks to the observed fifteen-significant-digit arithmetic boundary
Logarithms insist on positive arguments and a positive base; base one yields DIV/0, invalid domains or nonfinite results yield NUM, and existing error propagation and lazy IF or IFERROR branches stay available
Representable EXP subnormal values remain on offer in preview, whilst the existing materializer refuses subnormal output before publishing cells; saved zero caches serve no role as a numerical oracle for those native in-memory results
The qualified ordinary profile spans source and formula edits, supported calculated-field SUM dependencies, materialization, saving, reopening and native cached-value or explicit-refresh checks
Discrete manual groups take in MAX and MIN calculated-item measures beside SUM: member operands finalize through each measure aggregation, the calculated item pours into group subtotals and grand totals under that aggregation, and numeric-range or date groups keep their refusal
Ordinary numeric cell caches are written with seventeen significant digits: INT(-1E15-0.1) now persists its calculated -1000000000000001 through save and reopen, whilst preview and explicit native refresh keep their existing behaviour
Pivot cache source records and shared items still run through the existing fifteen-significant-digit numeric funnel and remain a separate qualification rather than a lossless output claim
MOD takes two arguments and hands back the exact binary remainder carrying the divisor sign: MOD(0.3,0.1) keeps 0.09999999999999998 and MOD(-0.3,0.1) keeps 2.7755575615628914e-17, subnormal results flush to zero, and quotients at or beyond 1125899906845 return NUM against the natively observed boundary
An edited cache-side calculated-item formula survives saving: the preserved raw cache definition is patched in place with the qualified native formula whilst every untouched byte keeps replaying, and the persisted formula becomes the new imported identity for later saves
Other aggregation, grouping and layout combinations keep the finite compatibility boundaries of their individual profiles
Cache ownership and binding
| Public declaration | Contract |
|---|---|
TXLSPivotCacheCalculatedItem | A cache-owned native calculated-member definition; obtain it through the owning cache and keep the cache alive for as long as you use the borrowed object |
TXLSPivotCacheCalculatedItem.FieldIndex: Integer | Read-only zero-based cache-field identity |
TXLSPivotCacheCalculatedItem.ItemIndex: Integer | Read-only zero-based shared-member identity within FieldIndex |
TXLSPivotCacheCalculatedItem.Formula: WideString | Read/write native member formula; assigning it changes the model, whilst preview or explicit binding validates syntax and dependency cycles before calculating |
TXLSPivotCacheCalculatedItem.ImportedFormula: WideString | Read-only formula exactly as imported from the file; a divergence from Formula marks an edited item whose raw cache part gets patched on save |
TXLSPivotCacheCalculatedItem.Supported: Boolean | Read-only availability of the parsed area identity, not a promise that every formula or view combination can be evaluated |
TXLSPivotCacheCalculatedItem.RawXml: WideString | Read-only preserved XML belonging to an unsupported calculated-item definition; known typed definitions carry an empty string |
TXLSPivotCache.AddCalculatedItem(AFieldIndex, AItemIndex: Integer; const AFormula: WideString): TXLSPivotCacheCalculatedItem | Creates a supported typed definition for an existing member, refusing invalid identities, an empty formula or a duplicate target identity; the returned object belongs to the cache |
TXLSPivotCache.FindCalculatedItem(AFieldIndex, AItemIndex: Integer): TXLSPivotCacheCalculatedItem | Returns the borrowed matching definition or nil |
TXLSPivotCache.CalculatedItemCount: Integer | Read-only number of retained supported or unsupported definitions |
TXLSPivotCache.CalculatedItems[Index: Integer]: TXLSPivotCacheCalculatedItem | Read-only zero-based borrowed access to the definition list |
TXLSPivotCache.ClearCalculatedItems | Frees the owned definitions and invalidates borrowed handles; shared members are not removed and cache query completeness is not established |
TXLSPivotCache.MoveCalculatedItem(AIndex, ANewIndex: Integer) | Moves an existing definition between zero-based positions in the native solve order, keeping its borrowed object identity; invalid positions raise EArgumentOutOfRangeException without any definitions being moved |
TXLSPivotCache._AddUnsupportedCalculatedItem(const ARawXml: WideString) | A parser-oriented preservation hook that retains unknown XML and marks the cache query model incomplete |
TXLSPivotCache.Assign(Source: TXLSPivotCache) | Deep-copies definitions, fields, shared members, record indices and date-system context; source handles stay independent, and assigning a cache to itself is safe |
TXLSPivotTable.BindCalculatedItemsToCache | Validates and binds view-authored calculated items on a detached cache, then appends the new shared members and definitions to the live cache; failures leave member identities and definitions untouched, whilst existing field and member handles stay valid |
A view-authored item created with TXLSPivotField.AddCalculatedItem needs an explicit BindCalculatedItemsToCache before native materialisation or typed native reconstruction; importing a supported native cache definition already brings that ownership with it
Cache binding touches every view sharing that cache, so treat it as an authoring operation and hold the borrowed handles only until the corresponding list is cleared, assigned or destroyed
Member filters and display transformations
Caption and value comparisons on a calculated-item field pick the displayed members after the member formulas have run; filtered source members stay available to referenced formulas, and visible subtotals and grand totals leave out those members' direct contributions
A value comparison can select a calculated measure; each candidate member evaluates that measure from its context dependency sums instead of adding source-record ratios or treating the formula as a cache record column
Calculated-item results also support the modelled ShowDataAs transformations, taking in percentages, index, differences, running totals, percentages of running totals and ranks; hidden members stay outside the visible running and rank sequences, whilst formula references keep their original values
| Public declaration | Contract |
|---|---|
TXLSPivotFilter.DataFieldIsMeasureIndex: Boolean | Selects the identity domain of DataField; False keeps the existing zero-based cache-field identity, whilst True identifies a zero-based displayed data-measure position and is set when native iMeasureFld is imported |
TXLSPivotFilter.SourceOrder: Integer | Read/write zero-based global order kept from the native filters element, defaulting to -1 when absent; local calculation and typed writing use nonnegative EvalOrder first, then SourceOrder, then stable field/list order |
Typed native writing converts a cache-field identity into its displayed measure position; a cache field feeding several data measures needs an explicit measure position, otherwise its aggregation and display identity would be ambiguous
Excel can save active filters with evalOrder=-1 whilst preserving their evaluation order through the filters element sequence; importing, cloning and typed reconstruction keep that sequence rather than treating those filters as inactive
Changing a filter definition, or its retained source position, on an imported preserved native view calls for typed reconstruction; ordinary native adoption validates the preserved filter identity and refuses unsupported edits before writing report cells
Preview, queries and date systems
function TXLSPivotTable.MakePreview(AWriter: TlxPivotResultWriter; ALayoutWriter: TlxPivotLayoutWriter; AUseNativeGrandTotals: Boolean = False; ABudget: TlxPivotQueryBudget = nil; ADateSystem: TXLSPivotDateSystem = xlpdsCache): Integer; function TXLSPivotTable.GetDataValue(const ADataField: WideString; const AConstraints: TXLSPivotDataConstraints; ABudget: TlxPivotQueryBudget; out AValue: Variant; ADateSystem: TXLSPivotDateSystem = xlpdsCache): Boolean;
MakePreview with AUseNativeGrandTotals=True uses a detached table and cache, exact native sums and calculated-item identities included; ordinary Make and default MakePreview keep their existing record-based calculation behaviour
GetDataValue turns to native context sums when the cache carries calculated fields or items, and GETPIVOTDATA shares that query path; neither operation refreshes source data, recalculates inspected worksheet formulas nor writes report cells
| Public declaration | Contract |
|---|---|
TXLSPivotCache.Date1904: Boolean | Read/write source date-system context for standalone native calculations; it defaults to False and is bound during Classic and XLSX import, worksheet cache creation and XLSX cache copying |
TXLSPivotDateSystem | Typed date-system selection for detached native previews and queries |
xlpdsCache | Use the cache's retained Date1904 context without altering it |
xlpds1900 | Project the 1900 date system into the detached calculation |
xlpds1904 | Project the 1904 date system into the detached calculation |
TryXLSXMakeNativePivotLayout(...; ADateSystem: TXLSPivotDateSystem = xlpdsCache): Boolean | The lower-level native layout helper takes the same detached date-system selection after its ResultXml and Reason output parameters |
TXLSGetDate1904 = function: Boolean of object | Calculator metadata callback reading the current owning workbook date system |
TXLSCalculator.OnGetDate1904: TXLSGetDate1904 | Optional borrowed callback used by GETPIVOTDATA; nil means cache context, whilst workbook evaluators and their read-only views supply the current workbook setting |
Standalone callers must supply the correct cache Date1904 context or an explicit date-system selection; workbook-owned native materialisation and formula queries project the current workbook setting without modifying the live cache
Date source values stay absolute TDateTime values in the cache, whilst native numeric formulas use Excel date serials; the 1904 system subtracts 1462 days per date value, and the 1900 conversion copes with the representable dates before March 1900
Saved native output ownership records its date-system context and compares styled date values against their serialised numeric payload; saving, reopening or changing the workbook date base preserves legitimate ownership, whilst changed date, Boolean, error and text payloads still refuse overwrite
Budgets and unsupported input
The optional TlxPivotQueryBudget callback receives work increments and a running memory estimate, covering the proposed detached snapshot and formula storage; False aborts with EXLSPivotQueryBudget and callback exceptions propagate
Record widths and database-member identities are checked before cloning; formula compilation and evaluation charge work, and the calculation keeps bounded syntax depth, formula text, calculated-member domains and accumulator storage
Calculated-item planning caps the combined member domains, caption storage and field plans before allocation; native member evaluation and late aggregate-filter scans likewise refuse proposed work above their fixed limits before entering those scans, and budget cancellation leaves live member masks unchanged
The formula parser handles numeric constants, field names, quoted names, field-qualified member names, arithmetic and comparisons, percent, plus ABS, SQRT, POWER, ROUND, MIN, MAX, SUM, IF, IFERROR, AND, OR and PI; unknown functions, cell references, arrays and unbound names are refused rather than being given guessed values
Native calculated fields call for SUM data measures and cannot serve as row, column or page axes; calculated items call for retained string captions in ungrouped cache fields, automatic or SUM subtotals, SUM measures and the supported single-member area identity
Unknown formula functions, nonzero area fieldPosition, unknown or malformed area metadata, ambiguous filter measure identities and mutually active basic and extended display transformations are refused explicitly; these restrictions do not turn an unsupported definition into an ordinary item
Late aggregate filtering of calculated members supports modelled value comparisons; the legacy count, percentage and sum filter variants and unmodelled Top n metadata call for a supported native selection model and are refused rather than substituting source-record comparisons
Imported raw parts keep unsupported future metadata for ordinary roundtrip preservation; local calculation, typed reconstruction and semantic feature extraction require an available model and never refresh source data to manufacture missing cache records
Semantic Pivot cache definitions take in calculated-item identity and formula, date-system context and detached bounded payloads; unavailable native extensions remain an explicit semantic error