电子表格的Google脚本(如果声明)

时间:2017-04-06 16:01:42

标签: javascript google-apps-script google-sheets

我希望有人可以帮我解决这个问题。我是编码的新手。我有一个谷歌电子表格,其中包含一个推送电子邮件的脚本。我试图让脚本忽略脚本已经发送电子邮件的行。

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Email Menu')
    .addItem('Send Email', 'myFunction')
    .addSeparator()
    .addToUi();
};

function myFunction() {
  var msg = 'Email sent!';

  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheet = ss.getActiveSheet();
  var range = sheet.getDataRange();
  var values = range.getValues();

  var EMAIL_SENT = "EMAIL_SENT";
  var startRow = 2;

  for (i=1; i<values.length;i++) {

    //sent = values[i][4]; //added this in to try and skip a row if "X" was in Sent Column

    //if (sent ==" ", ) //added this in to try and skip a row if "X" was in Send Column

    var email = values[i][0];
    var name = values[i][i];
    var subject = values[i][2];
    var body = values[i][3];
    var sent = values[i][5];

    if (sent != EMAIL_SENT){
      MailApp.sendEmail(email, subject, body);
      sheet.getRange(startRow + i,5).setValue(EMAIL_SENT);
      SpreadsheetApp.getUi().alert(msg);
    }
 }}

Google spreadsheet

2 个答案:

答案 0 :(得分:1)

小修复。取代

sheet.getRange(startRow + i,5).setValue(EMAIL_SENT); 

sheet.getRange(startRow + i - 1, 6).setValue(EMAIL_SENT); 

根据脚本的其余部分,这应该是最简单的修复。这假定sent列为F(第6列)而非E(第5列)。包含更新脚本的样本表为here

和!您应该将var name = values[i][i];更改为var name = values[i][1];,因为@jrook指出。我错过了......

答案 1 :(得分:1)

在for循环中实施以下更改:

for (i=1; i<values.length;i++) {

  var email = values[i][0];  
  var name = values[i][1]; //not [i][i] !  
  var subject = values[i][2];
  var body = values[i][3];  
  var sent = values[i][4];

  if (sent !== EMAIL_SENT){
    sheet.getRange(i+1,5).setValue(EMAIL_SENT);
  }

}

基本上摆脱startRow变量(如果你没有在其他地方使用),只需使用(i + 1,5)将“EMAIL_SENT”放在右栏中。为清楚起见,我删除了部分代码。