Last active
April 14, 2022 23:52
-
-
Save mbierman/9d81694761f4707a6210807b3151019f to your computer and use it in GitHub Desktop.
Keep Google Sheet under a fixed number of rows.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function acraCleanup() { | |
| var rowsToKeep = 1996; // CHANGE TO YOUR DESIRED NUMBER OF ROWS TO KEEP. | |
| var rows = SpreadsheetApp.getActiveSheet().getLastRow(); | |
| var numToDelete = rows - rowsToKeep -1; | |
| if ( numToDelete >= 1 ) { | |
| SpreadsheetApp.getActiveSheet().deleteRows(2, numToDelete); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // new version | |
| function acraCleanup() { | |
| const ss = SpreadsheetApp.getActive(); | |
| const sheet = ss.getSheetByName('Data'); | |
| const maxNumDataRows = 1986; | |
| const numHeaderRows = sheet.getFrozenRows() || 1; | |
| const numRows = sheet.getMaxRows(); | |
| const numRowsToDelete = numRows - numHeaderRows - maxNumDataRows; | |
| if (numRowsToDelete <= 0) { | |
| console.log(`🛑 Nothing to do: sheet '${sheet.getName()}' has ${numRows} rows, which is less than or equal to the allowed max of '${numHeaderRows + maxNumDataRows}'.`); | |
| return; | |
| } | |
| const rowStartKeep = numHeaderRows + 1 + numRowsToDelete; | |
| const rangeToKeep = sheet.getRange('A' + rowStartKeep + ':Z'); | |
| const target = sheet.getRange('A' + (numHeaderRows + 1)); | |
| rangeToKeep.copyTo(target); | |
| const rowStartDelete = numHeaderRows + 1 + maxNumDataRows; | |
| sheet.deleteRows(rowStartDelete, numRowsToDelete); | |
| console.log(`✂️ Pruned ${numRowsToDelete} rows at the end of sheet '${sheet.getName()}'.`); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment