Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 29 additions & 23 deletions docs/excel/excel-add-ins-data-validation.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
---
title: Add data validation to Excel ranges
description: Learn how the Excel JavaScript APIs enable your add-in to add automatic data validation to tables, columns, rows, and other ranges in a workbook.
ms.date: 02/16/2022
description: Use the Excel JavaScript API to programmatically apply and manage data validation rules for ranges, tables, and structured inputs.
ms.date: 09/19/2025
ms.localizationpriority: medium
---

# Add data validation to Excel ranges

The Excel JavaScript Library provides APIs to enable your add-in to add automatic data validation to tables, columns, rows, and other ranges in a workbook. To understand the concepts and the terminology of data validation, please see the following articles about how users add data validation through the Excel UI.
Use the Excel JavaScript API to enforce data quality. Apply rules and rely on Excel’s validation UI for prompts and error alerts. This article shows how to define rule types, configure prompts and error alerts, and remove or adjust validation. If you need background on Excel’s built-in validation UI, review these articles.

- [Apply data validation to cells](https://support.microsoft.com/office/29fecbcc-d1b9-42c1-9d76-eff3ce5f7249)
- [More on data validation](https://support.microsoft.com/office/f38dee73-9900-4ca6-9301-8a5f6e1f0c4c)
- [Description and examples of data validation in Excel](https://support.microsoft.com/help/211485)

## Programmatic control of data validation

The `Range.dataValidation` property, which takes a [DataValidation](/javascript/api/excel/excel.datavalidation) object, is the entry point for programmatic control of data validation in Excel. There are five properties to the `DataValidation` object:
The `Range.dataValidation` property, which takes a [DataValidation](/javascript/api/excel/excel.datavalidation) object, is the entry point for programmatic control of data validation in Excel. The object has five properties:

- `rule` — Defines what constitutes valid data for the range. See [DataValidationRule](/javascript/api/excel/excel.datavalidationrule).
- `errorAlert` — Specifies whether an error pops up if the user enters invalid data, and defines the alert text, title, and style; for example, `information`, `warning`, and `stop`. See [DataValidationErrorAlert](/javascript/api/excel/excel.datavalidationerroralert).
- `errorAlert` — Specifies whether an error pops up if the user enters invalid data, and defines the alert text, title, and style such as `information`, `warning`, and `stop`. See [DataValidationErrorAlert](/javascript/api/excel/excel.datavalidationerroralert).
- `prompt` — Specifies whether a prompt appears when the user hovers over the range and defines the prompt message. See [DataValidationPrompt](/javascript/api/excel/excel.datavalidationprompt).
- `ignoreBlanks` — Specifies whether the data validation rule applies to blank cells in the range. Defaults to `true`.
- `type` — A read-only identification of the validation type, such as WholeNumber, Date, TextLength, etc. It is set indirectly when you set the `rule` property.

> [!NOTE]
> Data validation added programmatically behaves just like manually added data validation. In particular, note that data validation is triggered only if the user directly enters a value into a cell or copies and pastes a cell from elsewhere in the workbook and chooses the **Values** paste option. If the user copies a cell and does a plain paste into a range with data validation, validation is not triggered.

## Creating validation rules
## Create validation rules

To add data validation to a range, your code must set the `rule` property of the `DataValidation` object in `Range.dataValidation`. This takes a [DataValidationRule](/javascript/api/excel/excel.datavalidationrule) object which has seven optional properties. *No more than one of these properties may be present in any `DataValidationRule` object.* The property that you include determines the type of validation.

Expand All @@ -38,10 +38,10 @@ The first three `DataValidationRule` properties (i.e., validation rule types) ta
- `decimal` — Requires a decimal number in addition to any other validation specified by the `BasicDataValidation` object.
- `textLength` — Applies the validation details in the `BasicDataValidation` object to the *length* of the cell's value.

Here is an example of creating a validation rule. Note the following about this code.
The following example creates a validation rule. Key points:

- The `operator` is the binary operator `greaterThan`. Whenever you use a binary operator, the value that the user tries to enter in the cell is the left-hand operand and the value specified in `formula1` is the right-hand operand. So this rule says that only whole numbers that are greater than 0 are valid.
- The `formula1` is a hard-coded number. If you don't know at coding time what the value should be, you can also use an Excel formula (as a string) for the value. For example, "=A3" and "=SUM(A4,B5)" could also be values of `formula1`.
- The `operator` is the binary operator `greaterThan`. Whenever you use a binary operator, the value that the user tries to enter in the cell is the left-hand operand and the value specified in `formula1` is the right-hand operand. This rule says that only whole numbers greater than 0 are valid.
- The `formula1` is a hard-coded number. If you don't know at coding time what the value should be, you can also use an Excel formula as a string (such as "=A3" or "=SUM(A4,B5)").

```js
await Excel.run(async (context) => {
Expand All @@ -59,9 +59,9 @@ await Excel.run(async (context) => {
});
```

See [BasicDataValidation](/javascript/api/excel/excel.basicdatavalidation) for a list of the other binary operators.
See [BasicDataValidation](/javascript/api/excel/excel.basicdatavalidation) for other binary operators.

There are also two ternary operators: `between` and `notBetween`. To use these, you must specify the optional `formula2` property. The `formula1` and `formula2` values are the bounding operands. The value that the user tries to enter in the cell is the third (evaluated) operand. The following is an example of using the "Between" operator.
There are also two ternary operators: `between` and `notBetween`. To use these, specify the optional `formula2` property. The `formula1` and `formula2` values are the bounding operands. The value that the user tries to enter in the cell is the third (evaluated) operand. The following is an example of using the "Between" operator.

```js
await Excel.run(async (context) => {
Expand Down Expand Up @@ -106,11 +106,11 @@ await Excel.run(async (context) => {

### List validation rule type

Use the `list` property in the `DataValidationRule` object to specify that the only valid values are those from a finite list. The following is an example. Note the following about this code.
Use the `list` property in the `DataValidationRule` object to constrain values to a finite set. The following code sample demonstrates. Key points:

- It assumes that there is a worksheet named "Names" and that the values in the range "A1:A3" are names.
- The `source` property specifies the list of valid values. The string argument refers to a range containing the names. You can also assign a comma-delimited list; for example: "Sue, Ricky, Liz".
- The `inCellDropDown` property specifies whether a drop-down control will appear in the cell when the user selects it. If set to `true`, then the drop-down appears with the list of values from the `source`.
- The `source` property specifies the list of valid values. The string argument refers to a range containing the names. You can also assign a comma-delimited list such as "Sue, Ricky, Liz".
- The `inCellDropDown` property specifies whether a drop-down control appears in the cell when the user selects it. If `true`, the drop-down appears with the list of values from the `source`.

```js
await Excel.run(async (context) => {
Expand All @@ -131,11 +131,12 @@ await Excel.run(async (context) => {

### Custom validation rule type

Use the `custom` property in the `DataValidationRule` object to specify a custom validation formula. The following is an example. Note the following about this code.
Use the `custom` property to specify a custom validation formula. The following is an example. Key points:

- It assumes there is a two-column table with columns **Athlete Name** and **Comments** in the A and B columns of the worksheet.
- To reduce verbosity in the **Comments** column, it makes data that includes the athlete's name invalid.
- `SEARCH(A2,B2)` returns the starting position, in string in B2, of the string in A2. If A2 is not contained in B2, it does not return a number. `ISNUMBER()` returns a boolean. So the `formula` property says that valid data for the **Comment** column is data that does not include the string in the **Athlete Name** column.
- It assumes a there is two-column table with columns **Athlete Name** and **Comments** in the A and B columns of the worksheet.
- To reduce verbosity in the **Comments** column, the rule makes data that includes the athlete's name invalid.
- `SEARCH(A2,B2)` returns the starting position in B2 of the string in A2. If A2 isn't contained in B2, it doesn't return a number.
- `ISNUMBER()` returns a boolean. So the `formula` property says that valid data for **Comments** is data that doesn't include the **Athlete Name** string.

```js
await Excel.run(async (context) => {
Expand All @@ -154,7 +155,7 @@ await Excel.run(async (context) => {

## Create validation error alerts

You can a create custom error alert that appears when a user tries to enter invalid data in a cell. The following is a simple example. Note the following about this code.
Create an error alert to guide the user when invalid data is entered. The following example creates a basic alert. Key points:

- The `style` property determines whether the user gets an informational alert, a warning, or a "stop" alert. Only `stop` actually prevents the user from adding invalid data. The pop-ups for `warning` and `information` have options that allow the user enter the invalid data anyway.
- The `showAlert` property defaults to `true`. This means that Excel will pop-up a generic alert (of type `stop`) unless you create a custom alert which either sets `showAlert` to `false` or sets a custom message, title, and style. This code sets a custom message and title.
Expand All @@ -181,7 +182,7 @@ For more information, see [DataValidationErrorAlert](/javascript/api/excel/excel

## Create validation prompts

You can create an instructional prompt that appears when a user hovers over, or selects, a cell to which data validation has been applied. The following is an example.
Create an instructional prompt that appears when the user selects the cell. This example tells the user about the positive number validation before they enter data.

```js
await Excel.run(async (context) => {
Expand All @@ -207,16 +208,21 @@ For more information, see [DataValidationPrompt](/javascript/api/excel/excel.dat
To remove data validation from a range, call the [Range.dataValidation.clear()](/javascript/api/excel/excel.datavalidation#excel-excel-datavalidation-clear-member(1)) method.

```js
myrange.dataValidation.clear()
myrange.dataValidation.clear();
```

It isn't necessary that the range you clear is exactly the same range as a range on which you added data validation. If it isn't, only the overlapping cells, if any, of the two ranges are cleared.
The range you clear doesn’t need to precisely match the range on which you added data validation. If the two ranges aren't an exact match, only overlapping cells are cleared.

> [!NOTE]
> Clearing data validation from a range will also clear any data validation that a user has added manually to the range.

## Next steps

- Combine validation with events: [Events](excel-add-ins-events.md).
- Add [conditional formatting](excel-add-ins-conditional-formatting.md) for stronger visual cues.

## See also

- [Excel JavaScript object model in Office Add-ins](excel-add-ins-core-concepts.md)
- [DataValidation Object (JavaScript API for Excel)](/javascript/api/excel/excel.datavalidation)
- [Range Object (JavaScript API for Excel)](/javascript/api/excel/excel.range)
- [Range Object (JavaScript API for Excel)](/javascript/api/excel/excel.range)
37 changes: 31 additions & 6 deletions docs/excel/excel-add-ins-delay-in-cell-edit.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,42 @@
---
title: Delay execution while cell is being edited
description: Learn how to delay the execution of the Excel.run function when a cell is being edited.
ms.date: 02/16/2022
description: Defer an Excel.run batch until the user leaves cell edit mode instead of failing with an error.
ms.date: 09/19/2025
ms.localizationpriority: medium
---


# Delay execution while cell is being edited

`Excel.run` has an overload that takes in a [Excel.RunOptions](/javascript/api/excel/excel.runoptions) object. This contains a set of properties that affect platform behavior when the function runs. The following property is currently supported.
When a user is actively editing a cell, some add-in operations may fail immediately. Use the `delayForCellEdit` option to queue the batch until the user exits cell edit mode instead of throwing an error.

`Excel.run` has an overload that takes an [Excel.RunOptions](/javascript/api/excel/excel.runoptions) object. It supports the following property relevant to this scenario.

- `delayForCellEdit`: When `true`, Excel queues the batch until the user exits cell edit mode. When `false`, the batch fails immediately if the user is editing. The default value is `false`.

## Behavior comparison

| User editing? | `delayForCellEdit = false` (default) | `delayForCellEdit = true` |
|---------------|------------------------------------|--------------------------|
| No | Batch runs immediately | Batch runs immediately |
| Yes | Batch fails (`InvalidOperation` error) | Batch waits; then runs after edit is committed or canceled |

- `delayForCellEdit`: Determines whether Excel delays the batch request until the user exits cell edit mode. When `true`, the batch request is delayed and runs when the user exits cell edit mode. When `false`, the batch request automatically fails if the user is in cell edit mode (causing an error to reach the user). The default behavior with no `delayForCellEdit` property specified is equivalent to when it is `false`.
## Example

```js
await Excel.run({ delayForCellEdit: true }, async (context) => { ... });
await Excel.run({ delayForCellEdit: true }, async (context) => {
const sheet = context.workbook.worksheets.getActiveWorksheet();
const range = sheet.getRange("A1");
range.values = [["Updated while user was editing elsewhere"]];
await context.sync();
});
```

## Guidance

- Use `delayForCellEdit` only when user-initiated commands may overlap active cell editing, such as with a ribbon button that triggers a bulk update.
- Consider showing a status indicator in your add-in if queued work may be lengthy.
- Avoid chaining multiple long-running delayed batches. This creates a perceived lag for your users.

## Next steps

Explore related user-state strategies in [Events](excel-add-ins-events.md), such as reacting to selection changes, and combine with `delayForCellEdit` to improve your add-in's robustness.
Loading