Clear or delete ranges using the Excel JavaScript API
This article provides code samples that clear and delete ranges with the Excel JavaScript API. For the complete list of properties and methods supported by the Range
object, see Excel.Range class.
Note
The Excel JavaScript API doesn't have a "Cell" object or class. Instead, the Excel JavaScript API defines all Excel cells as Range
objects. An individual cell in the Excel UI translates to a Range
object with one cell in the Excel JavaScript API. A single Range
object can also contain multiple contiguous cells. See Work with cells using the Excel JavaScript API to learn more.
Clear a range of cells
The following code sample clears all contents and formatting of cells in the range E2:E5.
await Excel.run(async (context) => {
let sheet = context.workbook.worksheets.getItem("Sample");
let range = sheet.getRange("E2:E5");
range.clear();
await context.sync();
});
Data before range is cleared
Data after range is cleared
Delete a range of cells
The following code sample deletes the cells in the range B4:E4 and shifts other cells up to fill the space that was vacated by the deleted cells.
await Excel.run(async (context) => {
let sheet = context.workbook.worksheets.getItem("Sample");
let range = sheet.getRange("B4:E4");
range.delete(Excel.DeleteShiftDirection.up);
await context.sync();
});
Data before range is deleted
Data after range is deleted
See also
Office Add-ins