# FFormula

> Language fallback: requested `ko-KR`; content is `en-US`.

- Human documentation: [https://docs.univer.ai/ko-KR/reference/facade/formula](https://docs.univer.ai/ko-KR/reference/facade/formula)

- Agent Markdown: [https://docs.univer.ai/ko-KR/reference/facade/formula.md](https://docs.univer.ai/ko-KR/reference/facade/formula.md)

- Requested language: `ko-KR`

- Content language: `en-US`

- Documentation version: `1.0.4`

- Source: [facade/formula.mdx](https://github.com/dream-num/documentation/blob/dev/content/reference/facade/formula.mdx)

---

This interface class provides methods to modify the behavior of the operation formula.

> This class should not be instantiated directly. Use factory methods on `univerAPI` instead.

`@univerjs-pro/engine-formula/facade` extends the core formula Facade with cross-unit Sheet and Base reference authoring.

## Access

Access through:

* [`FUniver.getFormula()`](https://docs.univer.ai/ko-KR/reference/facade/univer.md#getformula)

## Setup

Register [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) or a preset that includes it. In plugin mode, import `@univerjs/engine-formula/facade`. Additional methods below require their listed plugin packages. See [Facade setup](https://docs.univer.ai/ko-KR/guides/sheets/getting-started/facade.md).

## `@univerjs/engine-formula`

### `FFormula.calculationEnd`

Listening calculation ends.

```typescript
calculationEnd(callback: (functionsExecutedState: FormulaExecutedStateType) => void): IDisposable
```

**Parameters**

* `callback` — Required. The callback function to be called when the formula calculation ends.

**Returns**

The disposable instance.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.calculationEnd((functionsExecutedState) => {
  console.log('Calculation end', functionsExecutedState)
})
```

**Types:** [`IDisposable`](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts) · [`FormulaExecutedStateType`](https://unpkg.com/@univerjs/engine-formula/lib/types/services/runtime.service.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.calculationProcessing`

Listening calculation processing.

```typescript
calculationProcessing(callback: (stageInfo: IExecutionInProgressParams) => void): IDisposable
```

**Parameters**

* `callback` — Required. The callback function to be called when the formula calculation is in progress.

**Returns**

The disposable instance.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.calculationProcessing((stageInfo) => {
  console.log('Calculation processing', stageInfo)
})
```

**Types:** [`IDisposable`](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts) · [`IExecutionInProgressParams`](https://unpkg.com/@univerjs/engine-formula/lib/types/services/runtime.service.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.calculationResultApplied`

Listens for formula results after every affected model has applied them.

```typescript
calculationResultApplied(callback: (result: ISetFormulaCalculationResultMutation) => void): IDisposable
```

**Parameters**

* `callback` — Required. Receives each applied formula result asynchronously.

**Returns**

A disposable that unsubscribes from future result notifications.

**Types:** [`IDisposable`](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts) · [`ISetFormulaCalculationResultMutation`](https://unpkg.com/@univerjs/engine-formula/lib/types/commands/mutations/set-formula-calculation.mutation.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.calculationStart`

Listening calculation starts.

```typescript
calculationStart(callback: (forceCalculation: boolean) => void): IDisposable
```

**Parameters**

* `callback` — Required. The callback function to be called when the formula calculation starts.

**Returns**

The disposable instance.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.calculationStart((forceCalculation) => {
  console.log('Calculation start', forceCalculation)
})
```

**Types:** [`IDisposable`](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.executeCalculation`

Forces formula calculation explicitly.

Normal facade mutations such as `range.setFormula()` already mark formula
data dirty and schedule calculation automatically. Use this method only when
an external data change did not produce a dirty command or an explicit full
recalculation is required.

```typescript
executeCalculation(): void
```

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.executeCalculation()
```

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.executeFormulas`

Execute a batch of formulas asynchronously and receive computed results.

Each formula cell is represented as a string array:
\[fullFormula, ...subFormulas]

Where:

* fullFormula (index 0) is the complete formula expression written in the cell.
  Example: "=SUM(A1:A10) + SQRT(D7)".

* subFormulas (index 1+) are **optional decomposed expressions** extracted from
  the full formula. Each of them can be independently computed by the formula engine.

  These sub-expressions can include:

  * Single-cell references:  "A2", "B2", "C5"
  * Range references:        "A1:A10"
  * Function calls:          "SQRT(D7)", "ABS(A2-B2)"
  * Any sub-formula that was parsed out of the original formula and can be
    evaluated on its own.

  The batch execution engine may use these sub-formulas for dependency resolution,
  incremental computation, or performance optimizations.

```typescript
executeFormulas(formulas: IFormulaStringMap, timeout?: number): Promise<IFormulaExecuteResultMap>
```

**Parameters**

* `formulas` — Required.        Nested structure (unit → sheet → row → column) describing formulas and
  their decomposed sub-expressions.
* `timeout` — Optional. Default: `30_000`. Optional timeout in milliseconds. If no result is received within this
  period, the promise will be rejected.

**Returns**

A promise that resolves with the computed value map mirroring
the input structure.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
const formulas = {
  Book1: {
    Sheet1: {
      2: {
        3: [
          // Full formula:
          '=SUM(A1:A10) + SQRT(D7)',

          // Decomposed sub-formulas (each one can be evaluated independently):
          'SUM(A1:A10)', // sub-formula 1
          'SQRT(D7)', // sub-formula 2
          'A1:A10', // range reference
          'D7', // single-cell reference
        ],
      },
      4: {
        5: ['=A2 + B2 + SQRT(C5)', 'A2', 'B2', 'SQRT(C5)'],
      },
    },
  },
}

const result = await formulaEngine.executeFormulas(formulas)
console.log(result)
```

**Types:** [`IFormulaExecuteResultMap`](https://unpkg.com/@univerjs/engine-formula/lib/types/basics/common.d.ts) · [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts) · [`IFormulaStringMap`](https://unpkg.com/@univerjs/engine-formula/lib/types/basics/common.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.getAllDependencyTrees`

Retrieve all formula dependency trees that were produced during the latest
dependency-analysis run. This triggers a local dependency-calculation command
and returns the complete set of dependency trees once the calculation finishes.

```typescript
getAllDependencyTrees(timeout?: number): Promise<IFormulaDependencyTreeJson[]>
```

**Parameters**

* `timeout` — Optional. Default: `30_000`. Optional timeout in milliseconds. If no result is received within this
  period, the promise will be rejected.

**Returns**

A promise that resolves with the array of dependency trees.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

// Fetch all dependency trees generated for the current workbook.
const trees = await formulaEngine.getAllDependencyTrees()
console.log('All dependency trees:', trees)
```

**Types:** [`IFormulaDependencyTreeJson`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/dependency/dependency-tree.d.ts) · [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.getCellDependencyTree`

Retrieve the dependency tree of a specific cell. This triggers a local
dependency-calculation command for the given unit, sheet, and cell location,
and returns the computed dependency tree when the calculation is completed.

```typescript
getCellDependencyTree(param: { unitId: string; sheetId: string; row: number; column: number; }, timeout?: number): Promise<IFormulaDependencyTreeFullJson | undefined>
```

**Parameters**

* `param` — Required. The target cell location.
* `timeout` — Optional. Default: `30_000`. Optional timeout in milliseconds. If no result is received within this
  period, the promise will be rejected.

**Returns**

A promise that resolves with the dependency tree or `undefined`
if no tree exists for that cell.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

// Query the dependency tree for cell B2 in a specific sheet.
const tree = await formulaEngine.getCellDependencyTree({
  unitId: 'workbook1',
  sheetId: 'sheet1',
  row: 1,
  column: 1,
})

console.log('Cell dependency tree:', tree)
```

**Types:** [`IFormulaDependencyTreeFullJson`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/dependency/dependency-tree.d.ts) · [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.getFormulaExpressTree`

Parse a formula string and return its **formula expression tree**.

This API analyzes the syntactic structure of a formula and builds an
expression tree that reflects how the formula is composed (functions,
operators, ranges, and nested expressions), without performing calculation
or dependency evaluation.

The returned tree is suitable for:

* Formula structure visualization
* Explaining complex formulas (e.g. LET / LAMBDA)
* Debugging or inspecting formula composition
* Building advanced formula tooling

***

```typescript
getFormulaExpressTree(formulaString: string, unitId: string): IExprTreeNode | null
```

**Parameters**

* `formulaString` — Required. The formula string to parse (with or without leading `=`)
* `unitId` — Required. The workbook unit id used to resolve defined names and tables.

**Returns**

A formula expression tree describing the hierarchical structure of the formula

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

const formula = '=LET(x,SUM(A1,B1,A1:B10),y,OFFSET(A1:B10,0,1),SUM(x,y)+x)+1'

const exprTree = formulaEngine.getFormulaExpressTree(formula)

console.log(exprTree)
```

Example output (simplified):

```json
{
  "value": "let(x,sum(A1,B1,A1:B10),y,offset(A1:B10,0,1),sum(x,y)+x)+1",
  "children": [
    {
      "value": "let(x,sum(A1,B1,A1:B10),y,offset(A1:B10,0,1),sum(x,y)+x)",
      "children": [
        {
          "value": "sum(A1,B1,A1:B10)",
          "children": [
            {
              "value": "A1:B10",
              "children": []
            }
          ]
        },
        {
          "value": "offset(A1:B10,0,1)",
          "children": [
            {
              "value": "A1:B10",
              "children": []
            }
          ]
        }
      ]
    }
  ]
}
```

**Types:** [`IExprTreeNode`](https://unpkg.com/@univerjs/engine-formula/lib/types/basics/common.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.getInRangeFormulas`

Retrieve the dependency trees of all formulas *inside* the specified ranges.
Unlike `getRangeDependents`, this API only returns formulas whose definitions
physically reside within the queried ranges.

Internally this triggers the same dependency-calculation command but with
`isInRange = true`, and the promise resolves when the results are ready.

```typescript
getInRangeFormulas(unitRanges: IUnitRange[], timeout?: number): Promise<IFormulaDependencyTreeJson[]>
```

**Parameters**

* `unitRanges` — Required. An array of workbook/sheet ranges defining the lookup
  boundaries:
* `unitId`  The workbook ID.
* `sheetId` The sheet ID.
* `range`   The zero-based grid range.
* `timeout` — Optional. Default: `30_000`. Optional timeout in milliseconds. If no result is received within this
  period, the promise will be rejected.

**Returns**

A promise that resolves with an array of `IFormulaDependencyTreeJson`
describing every formula found in the provided ranges along with
their parent/child relationships.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

// Query all formulas that lie within A1:D20 in Sheet1.
const formulasInRange = await formulaEngine.getInRangeFormulas([
  {
    unitId: 'workbook1',
    sheetId: 'sheet1',
    range: { startRow: 0, endRow: 19, startColumn: 0, endColumn: 3 },
  },
])

console.log('Formulas inside range:', formulasInRange)
```

**Types:** [`IFormulaDependencyTreeJson`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/dependency/dependency-tree.d.ts) · [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts) · [`IUnitRange`](https://unpkg.com/@univerjs/core/lib/types/sheets/typedef.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.getRangeDependents`

Retrieve the full dependency trees for all formulas that *depend on* the
specified ranges. This triggers a local dependency-calculation command and
resolves once the calculation completes.

```typescript
getRangeDependents(unitRanges: IUnitRange[], timeout?: number): Promise<IFormulaDependencyTreeJson[]>
```

**Parameters**

* `unitRanges` — Required. An array of workbook/sheet ranges to query. Each range
  includes:
* `unitId`  The workbook ID.
* `sheetId` The sheet ID.
* `range`   The row/column boundaries.
* `timeout` — Optional. Default: `30_000`. Optional timeout in milliseconds. If no result is received within this
  period, the promise will be rejected.

**Returns**

A promise that resolves with an array of `IFormulaDependencyTreeJson`
representing formulas and their relationships within the dependency graph.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

// Query all formulas that depend on A1:B10 in Sheet1.
const dependents = await formulaEngine.getRangeDependents([
  {
    unitId: 'workbook1',
    sheetId: 'sheet1',
    range: { startRow: 0, endRow: 9, startColumn: 0, endColumn: 1 },
  },
])

console.log('Dependent formulas:', dependents)
```

**Types:** [`IFormulaDependencyTreeJson`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/dependency/dependency-tree.d.ts) · [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts) · [`IUnitRange`](https://unpkg.com/@univerjs/core/lib/types/sheets/typedef.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.getRangeDependentsAndInRangeFormulas`

Retrieve **both**:

1. the full dependency trees of all formulas that **depend on** the specified ranges, and
2. the dependency trees of all formulas that **physically reside inside** the specified ranges.

This is a convenience API that combines the behaviors of
`getRangeDependents` and `getInRangeFormulas` into a single call.

Internally, it triggers a local dependency-calculation command once and
resolves when both result sets are available, avoiding duplicate
calculations and event listeners.

```typescript
getRangeDependentsAndInRangeFormulas(unitRanges: IUnitRange[], timeout?: number): Promise<IFormulaDependentsAndInRangeResults>
```

**Parameters**

* `unitRanges` — Required. An array of workbook/sheet ranges to query. Each range
  includes:
* `unitId`  The workbook ID.
* `sheetId` The sheet ID.
* `range`   The zero-based row/column boundaries.
* `timeout` — Optional. Default: `30_000`. Optional timeout in milliseconds. If the dependency calculation does
  not complete within this period, the promise will be rejected.

**Returns**

A promise that resolves with an object containing:

* `dependents`: Dependency trees of all formulas that depend on the
  specified ranges (upstream consumers).
* `inRanges`: Dependency trees of all formulas whose definitions
  are located inside the specified ranges.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

const result = await formulaEngine.getRangeDependentsAndInRangeFormulas([
  {
    unitId: 'workbook1',
    sheetId: 'sheet1',
    range: { startRow: 0, endRow: 9, startColumn: 0, endColumn: 1 },
  },
])

console.log('Dependent formulas:', result.dependents)
console.log('Formulas inside range:', result.inRanges)
```

**Types:** [`IFormulaDependentsAndInRangeResults`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/dependency/dependency-tree.d.ts) · [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts) · [`IUnitRange`](https://unpkg.com/@univerjs/core/lib/types/sheets/typedef.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.lexerTreeBuilder`

The tree builder for formula string.

```typescript
readonly lexerTreeBuilder: LexerTreeBuilder
```

**Types:** [`LexerTreeBuilder`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/analysis/lexer-tree-builder.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.moveFormulaRefOffset`

Offsets the formula

```typescript
moveFormulaRefOffset(formulaString: string, refOffsetX: number, refOffsetY: number, ignoreAbsolute?: boolean): string
```

**Parameters**

* `formulaString` — Required. The formula string to offset
* `refOffsetX` — Required. The offset column
* `refOffsetY` — Required. The offset row
* `ignoreAbsolute` — Optional. Whether to ignore the absolute reference

**Returns**

The offset formula string

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
const result = formulaEngine.moveFormulaRefOffset('=SUM(A1,B2)', 1, 1)
console.log(result)
```

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.onCalculationResultApplied`

Waits until the latest formula-calculation results have been applied.

```typescript
onCalculationResultApplied(timeout?: number): Promise<void>
```

**Parameters**

* `timeout` — Optional. Maximum wait in milliseconds. Omit to wait without an overall timeout.

**Returns**

Resolves when the latest calculation results have been applied; rejects if the supplied timeout expires.

**Types:** [`Promise`](https://unpkg.com/@typescript/typescript-darwin-arm64/lib/lib.es5.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.sequenceNodesBuilder`

Resolves the formula string to a 'node' node

```typescript
sequenceNodesBuilder(formulaString: string): (string | ISequenceNode)[]
```

**Parameters**

* `formulaString` — Required. The formula string to resolve

**Returns**

The nodes of the formula string

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
const nodes = formulaEngine.sequenceNodesBuilder('=SUM(A1,B2)')
console.log(nodes)
```

**Types:** [`ISequenceNode`](https://unpkg.com/@univerjs/engine-formula/lib/types/engine/utils/sequence.d.ts)

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.setFormulaReturnDependencyTree`

Enable or disable emitting formula dependency trees after each formula calculation.

When enabled, the formula engine will emit the dependency trees produced by
each completed formula calculation through the internal command system.
Consumers can obtain the result by listening for the corresponding
calculation-result command.

When disabled, dependency trees will not be emitted.

This option only controls whether dependency trees are exposed.
It does not affect formula calculation behavior.

```typescript
setFormulaReturnDependencyTree(value: boolean): void
```

**Parameters**

* `value` — Required.        Whether to emit formula dependency trees after calculation.
  * `true`: Emit dependency trees after each calculation.
  * `false`: Do not emit dependency trees (default behavior).

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()

// Enable dependency tree emission
formulaEngine.setFormulaReturnDependencyTree(true)

// Listen for dependency trees produced by formula calculation
const trees = await new Promise<IFormulaDependencyTreeJson[]>((resolve, reject) => {
  const timer = setTimeout(() => {
    disposable.dispose()
    reject(new Error('Timeout waiting for formula dependency trees'))
  }, 30_000)

  const disposable = commandService.onCommandExecuted((command) => {
    if (command.id !== SetFormulaDependencyCalculationResultMutation.id) {
      return
    }

    clearTimeout(timer)
    disposable.dispose()

    const params = command.params as ISetFormulaDependencyCalculationResultMutation
    resolve(params.result ?? [])
  })
})

console.log('Dependency trees:', trees)
```

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.setMaxIteration`

When a formula contains a circular reference, set the maximum number of iterations for the formula calculation.

```typescript
setMaxIteration(maxIteration: number): void
```

**Parameters**

* `maxIteration` — Required. The maximum number of iterations. The default value is 1.

**Examples**

```ts
// Set the maximum number of iterations for the formula calculation to 5.
// The default value is 1.
const formulaEngine = univerAPI.getFormula()
formulaEngine.setMaxIteration(5)
```

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.stopCalculation`

Stop the calculation of the formula.

```typescript
stopCalculation(): void
```

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.stopCalculation()
```

**Package:** [`@univerjs/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs/engine-formula/lib/types/facade/f-formula.d.ts)

## `@univerjs/sheets-formula`

### `FFormula.registerAsyncFunction`

Register a custom asynchronous formula function.

```typescript
registerAsyncFunction(name: string, func: IRegisterAsyncFunction): IDisposable
registerAsyncFunction(name: string, func: IRegisterAsyncFunction, description: string): IDisposable
```

**Parameters**

* `name` — Required. The name of the function to register. This will be used in formulas (e.g., =ASYNCFUNC()).
* `func` — Required. The async implementation of the function.
* `description` — Optional. A string describing the function's purpose and usage.

**Returns**

A disposable object that will unregister the function when disposed.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.registerAsyncFunction(
  'RANDOM_DELAYED',
  async () => {
    await new Promise((resolve) => setTimeout(resolve, 500))
    return Math.random()
  },
  'Mock a random number generation function',
)

// Use the function in a cell
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getSheetByName('Sheet1')
if (!fWorksheet) throw new Error('fWorksheet is not available')
const cellA1 = fWorksheet.getRange('A1')
cellA1.setValue({ f: '=RANDOM_DELAYED()' })

// After 0.5 second, A1 will display a random number
```

```ts
// Mock a user score fetching function
const formulaEngine = univerAPI.getFormula()
formulaEngine.registerAsyncFunction(
  'FETCH_USER_SCORE',
  async (userId) => {
    await new Promise((resolve) => setTimeout(resolve, 1000))
    // Mock fetching user score from database
    return userId * 10 + Math.floor(Math.random() * 20)
  },
  {
    description: 'customFunction.FETCH_USER_SCORE.description',
    locales: {
      zhCN: {
        customFunction: {
          FETCH_USER_SCORE: {
            description: '从数据库中获取用户分数',
          },
        },
      },
      enUS: {
        customFunction: {
          FETCH_USER_SCORE: {
            description: 'Mock fetching user score from database',
          },
        },
      },
    },
  },
)

// Use the function in a cell
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getSheetByName('Sheet1')
if (!fWorksheet) throw new Error('fWorksheet is not available')
const cellA1 = fWorksheet.getRange('A1')
cellA1.setValue({ f: '=FETCH_USER_SCORE(42)' })

// After 1 second, A1 will display a score
```

**Types:** [`IDisposable`](https://unpkg.com/@univerjs/sheets-formula/lib/types/facade/f-formula.d.ts) · [`IRegisterAsyncFunction`](https://unpkg.com/@univerjs/engine-formula/lib/types/services/formula/register-function.service.d.ts)

**Package:** [`@univerjs/sheets-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/sheets-formula.md) · [Type definitions](https://unpkg.com/@univerjs/sheets-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.registerFunction`

Register a custom synchronous formula function.

```typescript
registerFunction(name: string, func: IRegisterFunction): IDisposable
registerFunction(name: string, func: IRegisterFunction, description: string): IDisposable
```

**Parameters**

* `name` — Required. The name of the function to register. This will be used in formulas (e.g., =MYFUNC()).
* `func` — Required. The implementation of the function.
* `description` — Optional. A string describing the function's purpose and usage.

**Returns**

A disposable object that will unregister the function when disposed.

**Examples**

```ts
// Register a simple greeting function
const formulaEngine = univerAPI.getFormula()
formulaEngine.registerFunction('HELLO', (name) => `Hello, ${name}!`, 'A simple greeting function')

// Use the function in a cell
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getSheetByName('Sheet1')
if (!fWorksheet) throw new Error('fWorksheet is not available')
const cellA1 = fWorksheet.getRange('A1')
cellA1.setValue('World')
const cellA2 = fWorksheet.getRange('A2')
cellA2.setValue({ f: '=HELLO(A1)' })

// A2 will display: "Hello, World!"
formulaEngine.calculationEnd((functionsExecutedState) => {
  if (functionsExecutedState === 3) {
    console.log(cellA2.getValue()) // Hello, World!
  }
})
```

```ts
// Register a discount calculation function
const formulaEngine = univerAPI.getFormula()
formulaEngine.registerFunction(
  'DISCOUNT',
  (price, discountPercent) => price * (1 - discountPercent / 100),
  'Calculates final price after discount',
)

// Use the function in a cell
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getSheetByName('Sheet1')
if (!fWorksheet) throw new Error('fWorksheet is not available')
const cellA1 = fWorksheet.getRange('A1')
cellA1.setValue(100)
const cellA2 = fWorksheet.getRange('A2')
cellA2.setValue({ f: '=DISCOUNT(A1, 20)' })

// A2 will display: 80
formulaEngine.calculationEnd((functionsExecutedState) => {
  if (functionsExecutedState === 3) {
    console.log(cellA2.getValue()) // 80
  }
})
```

```ts
// Registered formulas support lambda functions
const formulaEngine = univerAPI.getFormula()
formulaEngine.registerFunction(
  'CUSTOMSUM',
  (...variants) => {
    let sum = 0
    const last = variants[variants.length - 1]

    if (last.isLambda && last.isLambda()) {
      variants.pop()
      const variantsList = variants.map((variant) =>
        Array.isArray(variant) ? variant[0][0] : variant,
      )
      sum += last.executeCustom(...variantsList).getValue()
    }

    for (const variant of variants) {
      sum += Number(variant) || 0
    }

    return sum
  },
  'Adds its arguments',
)

// Use the function in a cell
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getSheetByName('Sheet1')
if (!fWorksheet) throw new Error('fWorksheet is not available')
const cellA1 = fWorksheet.getRange('A1')
cellA1.setValue(1)
const cellA2 = fWorksheet.getRange('A2')
cellA2.setValue(2)
const cellA3 = fWorksheet.getRange('A3')
cellA3.setValue({ f: '=CUSTOMSUM(A1,A2,LAMBDA(x,y,x*y))' })

// A3 will display: 5
formulaEngine.calculationEnd((functionsExecutedState) => {
  if (functionsExecutedState === 3) {
    console.log(cellA3.getValue()) // 5
  }
})
```

```ts
// Register a simple greeting function
const formulaEngine = univerAPI.getFormula()
formulaEngine.registerFunction('HELLO', (name) => `Hello, ${name}!`, {
  description: 'customFunction.HELLO.description',
  locales: {
    zhCN: {
      customFunction: {
        HELLO: {
          description: '一个简单的问候函数',
        },
      },
    },
    enUS: {
      customFunction: {
        HELLO: {
          description: 'A simple greeting function',
        },
      },
    },
  },
})

// Use the function in a cell
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getSheetByName('Sheet1')
if (!fWorksheet) throw new Error('fWorksheet is not available')
const cellA1 = fWorksheet.getRange('A1')
cellA1.setValue('World')
const cellA2 = fWorksheet.getRange('A2')
cellA2.setValue({ f: '=HELLO(A1)' })

// A2 will display: "Hello, World!"
formulaEngine.calculationEnd((functionsExecutedState) => {
  if (functionsExecutedState === 3) {
    console.log(cellA2.getValue()) // Hello, World!
  }
})
```

**Types:** [`IDisposable`](https://unpkg.com/@univerjs/sheets-formula/lib/types/facade/f-formula.d.ts) · [`IRegisterFunction`](https://unpkg.com/@univerjs/engine-formula/lib/types/services/formula/register-function.service.d.ts)

**Package:** [`@univerjs/sheets-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/sheets-formula.md) · [Type definitions](https://unpkg.com/@univerjs/sheets-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.setInitialFormulaComputing`

Update the calculation mode of the formula. It will take effect the next time the Univer Sheet is constructed.
The calculation mode only handles formulas data when the workbook initializes data.

```typescript
setInitialFormulaComputing(calculationMode: CalculationMode): void
```

**Parameters**

* `calculationMode` — Required. The calculation mode of the formula.

**Examples**

```ts
const formulaEngine = univerAPI.getFormula()
formulaEngine.setInitialFormulaComputing(0)
```

**Types:** [`CalculationMode`](https://unpkg.com/@univerjs/sheets-formula/lib/types/config/config.d.ts)

**Package:** [`@univerjs/sheets-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs/sheets-formula.md) · [Type definitions](https://unpkg.com/@univerjs/sheets-formula/lib/types/facade/f-formula.d.ts)

## `@univerjs-pro/engine-formula`

### `FFormula.buildReference`

Builds one Sheet-range or Base-table reference fragment for Facade authoring.

Use this method when the caller knows both the Host Unit ID and the stable
Source Unit ID. For a cross-Unit Source, it synchronously persists the
Host-owned External Reference before returning. For a Host-local Source, it
only returns local reference syntax. An unchanged binding is an idempotent
no-op.

The returned value is a reference fragment, not a complete formula: it has no
leading `=` and does not start calculation. The method does not load the Source
Unit. Formula calculation later reads the Source through its stable `unitId`.

Authoring rule:

* Cell formula: build the reference, then pass the returned fragment to
  `range.setFormula(...)`; the binding has already been persisted.
* Formula Shape: build the reference, then pass the same Source identity again
  in `shape.setFormula({ formula, externalReferences })`. The duplicate binding
  write is a no-op and the Shape setter remains the final consistency boundary.
* Hand-written or imported formula text: call `upsertExternalReference()` before
  writing the formula because the engine never guesses `unitId` from a name.

```typescript
buildReference(options: IBuildFormulaReferenceOptions): string
```

**Parameters**

* `options` — Required. Host, caller-provided source Unit, and reference target.

**Returns**

A formula reference fragment.

**Examples**

Write a cross-Unit Sheet reference to a cell

```ts
const workbook = univerAPI.getActiveWorkbook()
if (!workbook) throw new Error('No active workbook.')

const salesWorkbook = {
  unitId: 'sales-workbook',
  formulaQualifier: 'Sales Workbook',
}
const reference = univerAPI.getFormula().buildReference({
  hostUnitId: workbook.getId(),
  unit: salesWorkbook,
  target: {
    kind: univerAPI.Enum.FormulaReferenceType.SHEET_RANGE,
    sheetName: 'Sales',
    range: { startRow: 1, endRow: 9, startColumn: 1, endColumn: 1 },
  },
})
workbook.getActiveSheet().getRange('C1').setFormula(`=SUM(${reference})`)
```

Build a Host-local Sheet reference without creating a binding

```ts
const workbook = univerAPI.getActiveWorkbook()
if (!workbook) throw new Error('No active workbook.')

const reference = univerAPI.getFormula().buildReference({
  hostUnitId: workbook.getId(),
  unit: {
    unitId: workbook.getId(),
    formulaQualifier: workbook.getName(),
  },
  target: {
    kind: univerAPI.Enum.FormulaReferenceType.SHEET_RANGE,
    sheetName: 'Sales',
    range: { startRow: 1, endRow: 9, startColumn: 1, endColumn: 1 },
  },
})
// reference contains local syntax such as Sales!B2:B10.
```

**Types:** [`IBuildFormulaReferenceOptions`](https://unpkg.com/@univerjs-pro/engine-formula/lib/types/services/formula-reference-unit.service.d.ts)

**Package:** [`@univerjs-pro/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs-pro/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs-pro/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.removeExternalReference`

Removes one Host-owned External Reference by `referenceId` or `qualifier`.

Removing a binding does not rewrite or delete formulas. It marks only the Host
dirty; the next Host calculation resolves the remaining formula under the
normal External Reference rules.

```typescript
removeExternalReference(options: IRemoveHostExternalReferenceCommandParams): boolean
```

**Parameters**

* `options` — Required. Host plus reference ID or qualifier.

**Returns**

`true` when an existing binding was removed.

**Examples**

Remove a Host binding by qualifier

```ts
const workbook = univerAPI.getActiveWorkbook()
if (!workbook) throw new Error('No active workbook.')

const removed = univerAPI.getFormula().removeExternalReference({
  unitId: workbook.getId(),
  qualifier: 'Sales Workbook',
})
if (!removed) throw new Error('External Reference was not found.')
```

**Types:** [`IRemoveHostExternalReferenceCommandParams`](https://unpkg.com/@univerjs-pro/engine-formula/lib/types/commands/commands/host-external-reference.command.d.ts)

**Package:** [`@univerjs-pro/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs-pro/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs-pro/engine-formula/lib/types/facade/f-formula.d.ts)

### `FFormula.upsertExternalReference`

Creates or rebinds one Host-owned External Reference.

Use this explicit API when formula text is hand-written, imported, or generated
in a batch without `buildReference()`. Call it before writing the formula.
`qualifier` is the public name used inside the formula, without brackets or
quotes; `sourceUnitId` is the stable identity used for data requests.

Repeating the same mapping succeeds without mutation, dirty data, or undo.

```typescript
upsertExternalReference(options: IUpsertHostExternalReferenceCommandParams): boolean
```

**Parameters**

* `options` — Required. Host and stable Source binding.

**Returns**

`true` when the binding already matches or was persisted.

**Examples**

Bind a hand-written cross-workbook formula before writing it

```ts
const workbook = univerAPI.getActiveWorkbook()
if (!workbook) throw new Error('No active workbook.')

const formula = univerAPI.getFormula()
const bound = formula.upsertExternalReference({
  unitId: workbook.getId(),
  qualifier: 'Sales Workbook',
  sourceUnitId: 'sales-workbook',
  sourceUnitType: univerAPI.Enum.UniverInstanceType.UNIVER_SHEET,
})
if (!bound) throw new Error('Could not bind the Sales Workbook source.')

workbook.getActiveSheet().getRange('C1').setFormula("=SUM('[Sales Workbook]Sales'!B2:B10)")
```

**Types:** [`IUpsertHostExternalReferenceCommandParams`](https://unpkg.com/@univerjs-pro/engine-formula/lib/types/commands/commands/host-external-reference.command.d.ts)

**Package:** [`@univerjs-pro/engine-formula`](https://docs.univer.ai/ko-KR/reference/packages/plugins/univerjs-pro/engine-formula.md) · [Type definitions](https://unpkg.com/@univerjs-pro/engine-formula/lib/types/facade/f-formula.d.ts)
