# Formulas

This topic focuses on formula writes, calculation waits, and readback behavior inside `run`.

## What This Topic Is For

Use this topic when the task needs workbook-native recalculation and the result must remain consistent with how the workbook computes formulas.

## Formula Writes

You can write formulas with either of these APIs:

- `setFormula(formula) -> void`
- `setValue(value) -> FRange` when `value` starts with `=`

This applies to both:

- `range.setFormula('=SUM(B1:B10)')`
- `range.setValue('=SUM(B1:B10)')`

## Formula Calculation

Formula calculation is asynchronous. If you need the calculated result in the same `run`, wait for calculation to finish:

```javascript
await univerAPI.getFormula().onCalculationResultApplied();
```

Available formula wait API:

- `univerAPI.getFormula() -> FFormula`
- `onCalculationResultApplied() -> Promise<void>` - wait for formula-calculation results to be applied before reading the computed value
- note: if a real calculation runs, it resolves when results are applied; if no calculation starts quickly, it can resolve automatically instead of hanging forever

## Formula Warning

Without the wait, readback can be stale.

## Copyable Example

```javascript
async () => {
  const workbook = univerAPI.getActiveWorkbook();
  const sheet = workbook.getSheetByName("Sales");
  if (!sheet) return { success: false, error: 'Sheet "Sales" not found' };

  sheet.getRange("A1").setFormula("=SUM(B1:B10)");
  await univerAPI.getFormula().onCalculationResultApplied();

  return {
    success: true,
    formula: sheet.getRange("A1").getFormulas(),
    value: sheet.getRange("A1").getValue()
  };
};
```

## Formula Readback With setValue()

```javascript
async () => {
  const workbook = univerAPI.getActiveWorkbook();
  const sheet = workbook.getSheetByName("Sales");
  if (!sheet) return { success: false, error: 'Sheet "Sales" not found' };

  sheet.getRange("A2").setValue("=SUM(B2:B10)");
  await univerAPI.getFormula().onCalculationResultApplied();

  return {
    success: true,
    value: sheet.getRange("A2").getValue()
  };
};
```

## Getchas

- do not read the computed result immediately after writing a formula
- always verify formula output with workbook-visible reads after the command
- if the task is only propagation from an existing seed, prefer `ranges -> AutoFill` over custom formula scripting

## Related Topics

- See `ranges` for formula writes alongside value writes, shape rules, merges, clear, and AutoFill.
- See `overview` for hard rules and command-selection guidance.
