Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 756
rockinfreakshow Avatar asked Jun 01 '16 19:06

rockinfreakshow


1 Answers

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

like image 161
Alan Wells Avatar answered Sep 28 '22 05:09

Alan Wells