Ask Your Question
4

How can I use Office Script to delete all rows in Excel except for the first header row?

asked 2022-10-02 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-11-06 09:00:00 +0000

scrum gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-10-02 11:00:00 +0000

Seen: 8 times

Last updated: Nov 06 '21