This is my very first day messing around with google script so excuse my limitations.
I was trying to write a function that deleted all the rows in a Form Spreadsheet while leaving the header row behind.
Why does this work:
// Loop through the data in the range and delete the rows
if (data.length > 1) {
for (var row = 1; row < data.length; row++) {
ws.deleteRow(row+1);
}
ws.deleteRow(2);
}
While the following:
if (data.length > 1) {
for (var row = 1; row < data.length; row++) {
ws.deleteRow(row+1);
}
}
Leaves row 2 behind
Because the row indexes are 1-based (i.e., start at 1), you need to alter your for loop like this:
Assuming you have 2 rows, when you hit your second row in the loop (that is, when row = 2), the value of
rowwill not be less thandata.length(which is2); it will be equal to thedata.length. So with<, the test will fail and the code in the loop will not be executed that second time. With<=it will pass and code will be executed as desired.This same pattern will of course happen with any number of rows.
EDIT: a few other problems:
Because the removal will happen immediately, the rows will all shift after a removal and will be numbered differently. This can be handled in a couple ways, but here’s one: change your deletion to start from the end and work backwards. so, now we have:
Also, if you’re only trying to skip the first row, as the header row, rather that change the index used (e.g.,
row + 1), just change where you start/stop your loop. this is simpler and more understandable. so, the loop becomes: