Home > Software engineering >  setValue function skipping rows instead of choosing current in for loop
setValue function skipping rows instead of choosing current in for loop

Time:05-05

I have this code in Google Apps Script that is linked to a Google Sheet:

function sendReminders() {

  var sheet = SpreadsheetApp.openById('1IvXctYLXMKrSYPPSuMg_4_AQopemHPSnLHmQQgBDqH8').getSheetByName('ÉVALUATION');
  var startRow = 2;
  var numRows = sheet.getLastRow();
  var numColumns = sheet.getLastColumn();

  var dataRange = sheet.getRange(startRow, 1, numRows, numColumns);
  var data = dataRange.getValues();
  for (var i in data) {
    var row = data[i];
    var email = row[4];
    var ccEmail = row[5];
    var customId = row[1];
    var dueDate = Utilities.formatDate(new Date(row[9]), Session.getScriptTimeZone(), "yyyy-MM-dd");
    var message = 'Votre E&A est dûe pour la date suivante : '   dueDate   '. Merci de la compléter en cliquant sur le lien suivant : https://form.jotform.com/221156384847058?customId3='   customId;
    var emailSent = row[12];
    var value = Utilities.formatDate(new Date(row[10]), Session.getScriptTimeZone(), "yyyy-MM-dd");
    var today = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "yyyy-MM-dd");

    if (value == today && emailSent != 1) {
      var subject = 'Rappel - Enquête & Analyse';
      MailApp.sendEmail(email, subject, message, { cc: ccEmail });
      sheet.getRange((startRow   i), 13).setValue(1);
      SpreadsheetApp.flush();
    }
  }

}

The script is supposed to send reminder emails. Everything works well, except this one line:

sheet.getRange((startRow   i), 13).setValue(1);

This line should add the value of 1 to a specific cell in the Google Sheet, in the current row the for loop is at.

However, instead of adding the value to the current row, it skips rows and adds the value to some other row. In some cases, there's a difference of 18 rows, and in others, 198 rows.

Here is the enter image description here

Output:

enter image description here

Reference:

  • Related