I have the following code to copy the last row (effectively used as a template) and paste it a user-defined number of times into the sheet, effectively inserting new rows:
function InsertNewRows() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getActiveSheet();
var result = SpreadsheetApp.getUi().prompt('How many rows to enter?');
var numRows = result.getResponseText();
if (!numRows) {
SpreadsheetApp.getActive().toast("No value entered");
return;
}
for (i=1; i<=numRows; i=i+1) {
sheet.insertRowAfter(sheet.getLastRow()-1);
let sourceRange = sheet.getRange(sheet.getLastRow(),1,1,getLastCol());
sourceRange.copyTo(sheet.getRange(sheet.getLastRow()-1, 1));
}
SpreadsheetApp.getActive().toast(numRows+" row(s) added.","NEW ROWS ADDED");
};
The creation of a new row and the copy of the last row (basically everything inside the for loop) run very slowly. It's not a major issue since I don't expect to be adding a lot of rows, but can anyone shed light on ways it could be optimised?
Notes:
getLastCol()is a function to get the last column within a specific range (as distinct fromgetLastColumn())- In an earlier version of this, I had the
let sourceRange = ...line outside theforloop, but the contents of the cells were not being pasted properly, I think because the value ofgetLastRow()changed after I performedsheet.insertRowAfter