Google电子邮件脚本

时间:2017-03-10 09:06:21

标签: google-apps-script

我一直在尝试使用以下功能:

    // 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, 3)
  // 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
    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);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

在以下链接的Google教程中给出:https://developers.google.com/apps-script/articles/sending_emails 我想更改第6行,使其仅对指定的工作表起作用,而不是基于哪一个是活动的。在另一个论坛上向我建议将该行更改为:

var sheet = SpreadsheetApp.getSheetByName("sheetname");

但脚本编辑器找不到这样的命令。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您必须先打开电子表格,然后才能访问单张表格。如果您的脚本受文件限制,请尝试:

    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);

如果您使用的是独立脚本或需要引用其他电子表格,请尝试:

   var sheet = SpreadsheetApp.openById(id).getSheetByName(name)

希望这会有所帮助。