sheet.deleteRows() - Need to delete all the rows with data from top (preferably from 2nd row)

rockinfreakshow picture rockinfreakshow · Jun 1, 2016 · Viewed 20k times · Source

I need to delete 200-300 rows, excluding row 1. The script below is getting an out of bounds error, and it's slow. Can someone help with a way to speed up the process?

** IF POSSIBLE EXCLUDE ROW_1

function clearRange() {
  var sheet = SpreadsheetApp.getActive().getSheetByName('test');

  var start=1;
  var end=300;
  for (var i = start; i <= end; i++) 
    { sheet.deleteRow(i); }

}

SAMPLE SHEET - TAKE COPY

Answer

Alan Wells picture Alan Wells · Jun 1, 2016

Don't use a for loop. You can delete multiple rows in a Google Spreadsheet in one operation:

var start, howManyToDelete;

start = 2;//Hard coded row number from where to start deleting

howManyToDelete = sheet.getLastRow() - start + 1;//How many rows to delete -
      //The blank rows after the last row with content will not be deleted

sheet.deleteRows(start, howManyToDelete);

If you wanted to delete from row 2 to row 10, that is 9 rows to delete. The number of rows to delete must be 9. Only row 1 will be left after deleting row 2 to 10.

Apps Script Documentation