0

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

1 Answer 1

0

Because the row indexes are 1-based (i.e., start at 1), you need to alter your for loop like this:

for (var row = 1; row <= data.length; row++) {

Assuming you have 2 rows, when you hit your second row in the loop (that is, when row = 2), the value of row will not be less than data.length (which is 2); it will be equal to the data.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:

for (var row = data.length; row >= 1; row--) {

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:

 for (var row = data.length; row >= 2; row--) {
    ws.deleteRow(row);
 }
2
  • It works for the case when there are exactly 2 rows. However, if I add a third, row 2 is still not deleted without the extra line.
    – tanbog
    Nov 5, 2012 at 4:49
  • OK That fixed it thank you. I didn't realize it reordered the rows as it went.
    – tanbog
    Nov 5, 2012 at 5:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.