Clear Excel Cells with an Office Script Without Removing Formatting
Question details
Convert a VBA ClearContents macro into an Office Script that clears Excel cells without removing their formatting.

- Product
- Microsoft Excel for the web, Office Scripts
- Device & OS
- not provided
- Scenario
- The user wants to clear a continuous range or selected individual cells in an Excel workbook using Office Scripts.
- Observed behavior
- The desired result is to remove cell values and formulas while retaining existing formatting.
Open the workbook in Excel for the web and check that the Automate tab is available. Identify the worksheet and cell addresses you want to clear; the examples below use the active worksheet.
Clear a Continuous Range with Office Scripts
Use this approach to clear all values and formulas in a range while preserving cell formatting.
In Excel for the web, open the workbook, select the worksheet you want to edit, and choose Automate > New Script.
Replace the editor contents with: function main(workbook: ExcelScript.Workbook) { workbook.getActiveWorksheet().getRange("C2:C8").clear(ExcelScript.ClearApplyTo.contents); }
Choose Run in the script editor. Cells C2 through C8 will have their values and formulas cleared, but their formatting will remain.

Clear Individual Cells with Office Scripts
Use separate range calls when you want to clear specific cells without affecting the cells between them.
Edit Excel Workbooks with WPS Spreadsheet
WPS Office is a free, lightweight, easy-to-use Microsoft Office alternative with a familiar interface and Excel format compatibility for a smoother move between office suites. Office Scripts are a Microsoft Excel feature, so use Excel to run the scripts above.

Frequently Asked Questions
Does clearing contents remove formulas as well as values?
Yes. Range.clear(ExcelScript.ClearApplyTo.contents) removes both values and formulas from the specified cells while preserving formatting.
Can I clear cells on a specific worksheet instead of the active one?
Yes. Replace workbook.getActiveWorksheet() with workbook.getWorksheet("Sheet1"), using the name of your target worksheet.
Why not use clear() without an argument?
Calling clear() without an argument clears more than contents, including formatting. Specify ExcelScript.ClearApplyTo.contents to retain formatting.
Can I run my VBA macro directly as an Office Script?
No. VBA and Office Scripts use different languages and APIs. Create a new script under Automate > New Script and replace VBA commands with their Office Scripts equivalents.




