Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use Office Script to delete all rows in Excel except for the first header row by following these steps:

  1. Open the Excel file in Microsoft Excel Online.

  2. Click on the "Automate" tab in the ribbon and choose "Record a Macro".

  3. Click on the "Delete" button in the ribbon and choose "Delete Sheet Rows".

  4. Click on the first cell of the first row of data, then press and hold the "Shift" key and click on the last cell of the last row of data to select all rows.

  5. Click on the "Stop Recording" button in the ribbon to stop the macro recording.

  6. Open the "Script" tab in the ribbon and choose "New Script".

  7. In the script editor, replace the generated code with the following code:

function main(workbook: ExcelScript.Workbook) {
  let sheet = workbook.getActiveWorksheet();
  let range = sheet.getRange("A2:F"+sheet.getLastRow());
  range.delete(ExcelScript.DeleteShiftDirection.up);
}
  1. Save the script and run it by clicking on the "Run" button in the ribbon.

This code will delete all rows in the active worksheet except for the first header row. It does this by selecting all rows from the second row to the last row and deleting them, using the "up" parameter to shift the remaining rows upwards.