Google Script - 如果某个单元格被编辑,则自动发送电子邮件?

时间:2016-04-20 08:28:14

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

基本上我正在创建碳粉库存管理表,如果库存达到1,我就会收到要发送的电子邮件。它使用可安装的onEdit触发器执行此操作(我使用了简单的onEdit功能,可将调色剂添加到日志表中。我的电子邮件发送工作正常,但问题是如果一个股票减少到一个,它会在我每次编辑另一个股票时发送给我一封电子邮件。有没有办法只在包含相关库存号的单元格被更改时才运行电子邮件功能?

这是我的代码

function onEdit(event) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

    if(s.getName() == "Toners" && r.getColumn() == 5 && r.getValue() > "") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("Log");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    }
}

//I included the above code just in case someone finds an easier way to put it in there and then call the EmailPrinterGroup1 functon..




function EmailPrinterGroup1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var PrinterGroupStock = ss.getSheetByName("Notification").getRange("B1").getValue();
  var EmailList = ["abc@123.org"];
  if(PrinterGroupStock <= 1){
      var email = Session.getActiveUser().getEmail();
      GmailApp.sendEmail(EmailList, 'Toner Stock Alert - Communal Areas',
                        'There is only 1 toner left in stock for the communal areas, please re-stock ASAP. Click the link below to go to the Toner Stock Management sheet. \n\n'+ss.getUrl(),
                        {from:"xyz@321.org"});
      PropertiesService.getScriptProperties().setProperty("last", PrinterGroupStock);
    }
}

在这种情况下,我要检查的单元格是B1,它使用COUNTIF公式(如果计算结果为1,则会发送电子邮件),并且它是关于&#34;通知&#34;工作表(最常被编辑的主要工作表页面称为&#34; Toners&#34 ;.)谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用工作表中的单元格来存储一个标记,该标记会记住B1的值之前是否为1。在以下示例中,我使用的是A1

function onEdit(event) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

    if(s.getName() == "Toners" && r.getColumn() == 5 && r.getValue() > "") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("Log");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    }

  var stock_range = ss.getSheetByName("Notification").getRange(1, 2);
  var stock_is_one_flag = ss.getSheetByName("Notification").getRange(1, 1).getValue();

  if (stock_range.getValue() === 1 && stock_is_one_flag === 0){
    EmailPrinterGroup1();
    ss.getSheetByName("Notification").getRange(1, 1).setValue(1);
  } else if (stock_range.getValue() != 1 && stock_is_one_flag != 0){
    EmailPrinterGroup1();
    ss.getSheetByName("Notification").getRange(1, 1).setValue(0);
  }
}