根据单元格的返回发送电子邮件,如果声明谷歌表格

时间:2017-06-13 23:23:07

标签: excel google-apps-script google-sheets google-apps google-sheets-api

我的示例sheet

当D列中的任何单元格为" WINNER"时,我想向收件人1发送电子邮件。另外,当E列中的任何单元格为" WINNER"时,我想向收件人2发送一封电子邮件。当我手动输入" WINNER"在列D或E中的任何单元格中。但是,当单元格更改为" WINNER"时,它不起作用。作为if语句的结果。我尝试将脚本更改为true而不是" WINNER",但这也无效。

/**
 * add trigger for onedit -
  * see menu -> Resouces -> Current project's triggers
 */
function Initialize() {

  var triggers = ScriptApp.getProjectTriggers();

  for(var i in triggers) {
    ScriptApp.deleteTrigger(triggers[i]);
  }


  ScriptApp.newTrigger("sendNotification")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onEdit()
  .create();

  ScriptApp.newTrigger("sendNotification2")
  .forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
  .onEdit()
  .create();

};


/**
 *
 */

function sendNotification(f) {


  if("D" == f.range.getA1Notation().charAt(0)) {

    if(f.value == "WINNER") {

//Define Notification Details
      var recipients = "adam@gmail.com";
      var subject = "Update"+f.range.getSheet().getName();
      var body = "Adam just won the lottery!";

  //Send the Email
      MailApp.sendEmail(recipients, subject, body);
    }
  }
}

function sendNotification2(f) {


  if("E" == f.range.getA1Notation().charAt(0)) {

    if(f.value == "WINNER") {



  //Define Notification Details
      var recipients = "geo@gmail.com";
      var subject = "Update"+f.range.getSheet().getName();
      var body = "Geo just won the lottery!";

  //Send the Email
      MailApp.sendEmail(recipients, subject, body);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您可以查看此thread。您可以使用在计时器触发器上运行的简单脚本,并检查工作表中特定列的任何修改。

示例代码:

function checkColumnF() {
  var sh = SpreadsheetApp.getActiveSheet();
  var values = sh.getRange('F1:F').getValues().join('-');
  if(PropertiesService.getScriptProperties().getKeys().length==0){ // first time you run the script
    PropertiesService.getScriptProperties().setProperty('oldValues', values);
    return;
  }
  var oldValues = PropertiesService.getScriptProperties().getProperty('oldValues').split('-');
  var valuesArray = values.split('-');
  while (valuesArray.length>oldValues.length){
    oldValues.push('x'); // if you append some rows since last exec
  }
  Logger.log('oldValues = '+oldValues)
  Logger.log('current values = '+valuesArray)
  for(var n=0;n<valuesArray.length;n++){
    if(oldValues[n] != valuesArray[n]){ // check for any difference
      sendMail(n+1,valuesArray[n]);
    }
  }  
  PropertiesService.getScriptProperties().setProperty('oldValues', values);
}

function sendMail(row,val){
  Logger.log('value changed on row '+row+' value = '+val+' ,  mail sent');
  // uncomment below when you are sure everything runs fine to avoid sending dozens of emails while you test !
  //MailApp.sendEmail(Session.getActiveUser().getEmail(),'value changed in your sheet','Row '+row+' is now '+val);
}

其他参考:Email notifications with body/subject containing cell value