Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-api

Delete ALL Rows from a GSheet (empty and not empty)


How can I delete ALL rows in a google sheet using a script. The sheet.deleteRows() formula assumes I know the number of rows.

enter image description here

As shown in this example, the table is already sorted and I can delete all rows from the last table row (CTRL+DOWN). I can't use the For...Next loop, otherwise I'll run into the GScript timeout.

Is there a command that can jump directly to the last line to determine the number?

Thanks in advance


Solution

  • For your particular example you could use the following code as a reference:

    function myFunction() {
      var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // Change the name to the one you have in your Spreadsheet
      var dataRange = ss.getRange("A1:B4");
      ss.deleteRows(dataRange.getLastRow()+1, ss.getMaxRows()-ss.getLastRow());
      ss.deleteColumns(dataRange.getLastColumn()+1, ss.getMaxColumns()-ss.getLastColumn());
    
    }
    

    References: