删除行应用脚本仅第二次通过

时间:2018-03-18 16:34:08

标签: google-apps-script

因此,此应用程序脚本用于从电子邮件刻度表发送电子邮件并将其移至电子邮件日志表。

它似乎正在工作,除了我需要运行它两次才能删除标记为“email sent”的行。第一次,日志说这些行仍然说“准备好”,但然后再次运行它。

感谢您的帮助

 function sendEmails() {
  var ss = SpreadsheetApp.getActiveSpreadsheet ();
  var sheet = ss.getSheetByName("Email Que");
var rows = sheet.getLastRow()-1;
  var startRow = 3;  // First row of data to process
  var numRows = rows;   // Number of rows to process
  var now = new Date();

  var destSheet = ss.getSheetByName("Email Log");

  // Fetch the range of cells
  var dataRange = sheet.getRange(startRow, 10, numRows, 9)

  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  var emailSent = "Email Sent";
  var ready = "Ready";
  for (var i = 0; i < data.length; i++) {
    var row = data[i];
    var subj = row[0];
    var body = row[1]; 
    var studentEmail = row[4];
    var instEmail = row[5];
    var subEmail = row[6];
    var emailStatus = row[7];
    Logger.log("sending:" + emailStatus);
    if (emailStatus != emailSent && emailStatus == ready) {

      MailApp.sendEmail(studentEmail, subj, body);
      sheet.getRange(startRow + i, 17).setValue(emailSent);
      sheet.getRange(startRow + i, 18).setValue(now);
      var source = sheet.getRange (startRow + i,1,1,21);
      var lastRow = destSheet.getLastRow();
       destSheet.insertRowAfter(lastRow);
      source.copyTo(destSheet.getRange(lastRow + 1,1), {contentsOnly: true});

    };
  };






  for(var i = data.length-1;i>=0;i--){
      var row = data[i];
    var emailStatus = row[7];
Logger.log(emailStatus);
    if(emailStatus == emailSent)
      sheet.deleteRow(i+3);
    //2 header rows
  };
};

1 个答案:

答案 0 :(得分:1)

删除行需要额外执行,因为您在删除检查中引用了原始工作表状态 - 在写回状态之前,data已被读入内存。

您可以通过以下两种方式解决:通过重新查询工作表的状态,在删除循环之前刷新data变量:

SpreadsheetApp.flush() // Ensure pending writes are complete.
data = dataRange.getValues()

您也可以通过在发送电子邮件时更新data中的相关数组索引来执行此操作:

data[i][7] = /* the email status */;
data[i][8] = /* the email time */;