Search code examples
google-apps-scriptgoogle-sheetsdelete-row

How to Delete older rows on Form input data


I have 2 sheets in a Google workbook. A form inputs data to Sheet2, and a cell on Sheet1 shows the value of the cell in col B in the last row of Sheet2.

Sheet2:

1 Timestamp | UUID:
2 SomeDate1 | 0d6d7761-8540-1c5a-072b-f32868eb7f9b
3 SomeDate2 | d6b0df12-8dc9-eeff-5eef-ad064868fb31
4 SomeDate3 | a64ac46a-bb53-f540-f526-01cb48dac8f2
5 SomeDate4 | 826b3c6d-45cc-1b11-f2cd-e2a91eba091b
6 SomeDate5 | 00965bc4-77a1-aa87-52cd-ba11f472aa32

Sheet 1:

1 UUID:    | =INDEX(FILTER(Sheet2!B1:B,NOT(ISBLANK(Sheet2!B1:B))),COUNTA(Sheet2!B1:B))
              (which shows correctly as 00965bc4-77a1-aa87-52cd-ba11f472aa32)

When a form submission adds a new row to Sheet2, I need to delete older rows automatically, in some way.

After reading several pages of similar questions on StackExchange, I've learned that scripts can not delete Form input data, but a work-around is to use a time-driven Trigger. (How to delete row when a cell is modified?)

So, I found this script and added it, naming it DeleteOldRows.gs:

    function acraCleanup() {
    var rowsToKeep = 2; //NUMBER OF ROWS TO KEEP
    var rows = SpreadsheetApp.getActiveSheet().getLastRow();
    var numToDelete = rows - rowsToKeep -1;
    SpreadsheetApp.getActiveSheet().deleteRows(2, numToDelete);
    }

I then set a Timer trigger, to run that script.

The timer execution log shows the error "Exception: Those rows are out of bounds. at acraCleanup(DeleteOldRows:5:33)" which would be "deleteRows(2, numToDelete)"

Is the script incorrect, or is the error due to the fact the data is input via a Form?

Also, I have other sheets in the workbook with other data, and I need to make sure that the script only deletes the older rows on Sheet2, but I'm not sure how to specify that. I tried replacing "getActiveSheet()" with "getSheetByName('Sheet2')" and the error said "getSheetByName is not a function". Same with "getSheet('Sheet2')".


Solution

  • function deleteAllOldRows() {
      const ss = SpreadsheetApp.getActive();
      const sh = ss.getSheetByName('Form Responses 9');
      const lr = sh.getLastRow();
      if(lr - 2)sh.deleteRows(2,lr-2);
    }