I am having trouble with using Google Apps Script and the two functions the deleteRow()
and deleteRows()
methods.
The code below uses a string matches testing if a string exists in column. If the string exists then I want to do something, in this case delete a couple of rows in my active sheet.
The problem is that it deletes the first row or one row, then does not seem to delete the next row in my code below.
I have been able to verify that even if I do sheet from the end of the sheet starting at last row and going to first row or like below from first row to last row the same problem exist.
It deletes one row but never deletes more then one row. In my case no error is produced just row does not get deleted using either method.
var data = ws.getRange("A2:U" + ws.getLastRow()).getValues();
var i = 0;
var W = 23;
var deleted = "DELETED";
var sheetDataAsArr = SpreadsheetApp.getActiveSheet().getDataRange().getValues(); // 2020Members
sheetDataAsArr.forEach(function(row,i) {
// The i is a index
if ( row[W] = 'DELETED' ) {
// DO SOMETHING HERE
Logger.log('EMAIL DELETED ROW row is :' + row[B]); // The email
ws.deleteRow(i+1); // It deleted the record
i--; // Decrement i because record was deleted
}
i++;
});
The problem is very strange, I have been able to duplicate using both functions. It does not delete the next row but I get to see the next row because I show the correct email address but does not do the delete the second time through the loop but also does not produce any error message just does not do the delete the second one but deletes the first row just fine.
It only allows me to delete one row and no more then one row
var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("2020Members");
The following above works fine now
var myValue = ws.getRange(i+1, W).getValue();
This is the value in the sheet in the W column and the if works now also !
Whether I go from the last row to the first row but not the header and it still only allows me to delete one row and stop on the next row so if i traverse the sheet from first to last or last to first it only will not let me delete only one row and stops.
Do I need to sleep
or flush
something before doing the second delete?
Second example of code above I even tried to use ws.deleteRows(i+1,1);
and same problem happens.
The following above works fine now
var myValue = ws.getRange(i+1, W).getValue();
This is the value in the sheet in the W column and the if works now also !