Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to clear/delete data after a given row index in Google Spreadsheets

I would like to delete all data after row [x]. For example if the x = 355, I want all data to be deleted after 355th row.

I am able to delete all content in a simple sheet in google spreadsheet with:

var sheet = ss.getSheetByName('foo');
sheet.clearContents();

I’ve tried to do it with getRange method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var range = SpreadsheetApp
               .getActive()
               .getSheetByName("foo")
               .getRange("A20:E71");
range.clearContent();

but this is simply deleting inside data from A20:E71. What I want is to delete all data after A20th row.

>Solution :

Try:

  const sheet = SpreadsheetApp.getActiveSpreadsheet()
                              .getSheetByName(`foo`)
  
  sheet.getRange(21, 1, sheet.getLastRow()-20, sheet.getLastColumn())
       .clearContent()

The range is defined as all rows beyond the equivalent of A20.

Function:

function myFunction(allRowsAfter) {

  const sheet = SpreadsheetApp.getActiveSpreadsheet()
                              .getSheetByName(`foo`)
  
  sheet.getRange(allRowsAfter+1, 1, sheet.getLastRow()-allRowsAfter, sheet.getLastColumn())
       .clearContent()

}

myFunction(20); // Delete all rows after 20

See:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading