为什么我的emailSent字段写入第20行而不是第2行?

时间:2014-12-02 15:42:40

标签: javascript

我的代码似乎工作正常,除了第22行,它将“emailSent”值写入脚本运行的Google电子表格的第20行,而不是该电子表格的第2行,这是唯一的行有数据。有什么想法吗?

function sendEmails2() {
  //trying to adopt code from this tutorial https://developers.google.com/apps-script/articles/sending_emails
  //-believe there is an issue with where I am declaring getRange to work-
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var lastRow = 40;   // Last row of data to process
  // Fetch the range of cells A1:B10002
  var dataRange = sheet.getRange(startRow, 1, lastRow, 10)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  var i = data.length; 
  for (i in data) {
    var row = data[i];
    var emailAddress = row[7];  // raised an error at one point 
    var isEmailSent = row[9];     //
    var partTimeApproved = row[0]
    if (partTimeApproved != '') { // prevents sending emails to non-approved rows. for some reason = 'Y' doesn't work but !='' does //... or does it
    if (isEmailSent == '') {  // Prevents sending duplicates and sending emails to non-approved rows
      var subject = "Email Subject Test";
      var message = "Email body test";    // Standard string
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 10).setValue('emailSent'); //this didn't work: -replacing startRow + i with row-
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
  }
}

我理解,虽然我采用的代码使用

getrange(startRow + i, 10).setValue('emailSent'); 

然而,我不明白如何找到第20行,我不知道如何继续修复它。

1 个答案:

答案 0 :(得分:0)

第一

var i = data.length; <-- makes no sense
for (i in data) {    <-- since you override i here

我不知道实际上是什么数据。我假设它是一个带数字的字符串数组。 AKA ['0','1']

所以,当你期待2并且你得到20时,听起来你正在为一个数字添加一个字符串

> 2 + "0"
"20"

将其转换为数字。

> 2 + parseInt("0", 10)
2

所以在代码中:

getrange(startRow + parseInt(i, 10), 10).setValue('emailSent');