如何通过Google Apps脚本获取Google电子表格的行号?

时间:2013-08-16 07:11:11

标签: google-apps-script google-sheets

我有一个我正在使用的谷歌脚本,我想将我正在使用的当前行插入一个值,该值将重新添加到我在电子表格中设置的公式中。我想这样做以防有人重新提交相同的数据,因此他们会通过电子邮件发送更改。目前这个脚本只是我的概念证明,所以我可以继续编写整个过程。

我对脚本的问题是使用值currentRow。它似乎获得了第一遍的值,然后没有改变它,当你有多个条目需要处理时,这是有问题的。

我在变量RESEND_EMAIL中使用值currentRow,因此它可以生成一个公式,查看两列是否相似(我将使用日期时间戳并在第一次将其复制到D列(也称为var resend [4])。

这样我可以将脚本设置为自动运行并检查此列是否设置为“是”,在这种情况下,它将再次发送和发送电子邮件,然后更改一个值(此处显示为电子邮件地址 - 但我会改为使用时间戳),以便公式RESEND_EMAIL更改重新发送回“否”。

如何在currentRow值中始终使用正确的行号?

// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = "EMAIL_SENT";

function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2;  // First row of data to process
  var numRows = 2;   // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 6)
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[0];  // First column
    var message = row[1];       // Second column
    var emailSent = row[2];     // Third column
    var resend = row[4];
    var extension = row [5];
    var currentRow = sheet.getActiveRange().getRow();
    var RESEND_EMAIL = "=IF(A"+ currentRow +"=D" + currentRow +",\"No\",\"Yes\")";


    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      var subject = "Sending emails from a Spreadsheet";
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
      sheet.getRange(startRow + i, 5).setFormula(RESEND_EMAIL);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
    if (resend == "Yes") {  // Prevents sending duplicates
      var subject = "Sending emails from a Spreadsheet";
      message = message + " " + extension;
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 4).setValue(emailAddress);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }     

  }
}

1 个答案:

答案 0 :(得分:0)

如您的代码i所示,变量值将成为当前行。

...
var currentRow = startRow + i;
...