如果单元格包含“X”,则从Google表格发送电子邮件

时间:2016-10-25 10:32:49

标签: google-apps-script google-sheets

我有一个基于Google's tutorial的简单脚本,用于从工作表发送电子邮件。我想添加一个声明,只有当另一个单元格包含值“3”或更高时,才会调用它。

我猜我需要包含类似

的内容
if(sheet.getRange(6,5,numRows).getValue()>=3

这是当前的脚本

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


function SendEmail() {
  var ui = SpreadsheetApp.getUi();
  var file = SpreadsheetApp.getActive();
  var sheet = file.getSheetByName("Overview");  //Fetch appropriate sheet from workbook
  var startRow = 6; //First row of data to process
  var numRows = 60; //Number of rows to process
  //Fetch the range of cells E6:H60
  var dataRange = sheet.getRange(startRow, 5, numRows, 3);
  //Fetch values for each row in the Range
  var data = dataRange.getValues();
  for (var i=0; i < data.length; ++i) {
   // WHERE DOES THIS FIT??? if(sheet.getRange(6,5,numRows).getValue()>=3){      //change row and column in get range to match what you need
    var row = data[i];
    var emailAddress = row[0]; // Fifth column
    var emailSent = row[3]; // Eighth Column
    if (emailSent != EMAIL_SENT) {  // Prevents sending duplicates
      MailApp.sendEmail(emailAddress, "Subject!", "Message here");
      sheet.getRange(startRow + i, 8).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
    }
  }
//}

sheet image

感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:1)

我重写了剧本。希望你喜欢! :)

var COLUMN_EMAIL_SENT = 7;
var COLUMN_VALIDATION = 5;
var COLUMN_EMAILADDRESS = 1;
var SHEET_NAME = "Overview";
var EMAIL_SENT = "EMAIL_SENT";

function sendEmail() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
  var values = sheet.getDataRange().getValues();
  for(var i=0;i<values.length;i++) {
    var row = values[i];
    var emailAddress = row[COLUMN_EMAILADDRESS-1];
    if(emailAddress && !(row[COLUMN_EMAIL_SENT-1] === EMAIL_SENT) && parseInt(row[COLUMN_VALIDATION-1],10) >= 3) {
      MailApp.sendEmail(emailAddress, "Subject!", "Message here");
      sheet.getRange(i + 1, COLUMN_EMAIL_SENT + 1).setValue(EMAIL_SENT);
    }
  }
}