在google工作表的google脚本中的特定工作表上使用onedit()触发器

时间:2014-11-24 15:06:26

标签: function if-statement google-apps-script triggers google-sheets

我需要运行一个由onedit()触发的脚本,只运行一个页面。

我尝试过以下操作,但目前我无法让脚本只处理所需的工作表("库存")我确信这对于知道的人来说非常简单: / p>

function onEdit(e) {
    var range = e.range;
    if(range.getSheetName() == "Inventory") {
        if(range.getValue() == "notify") {
            range.setBackgroundColor('red');
            var productname = range.offset(0,-3).getValue();
            var productinventory = range.offset(0,-2).getValue();
            var message = "Product variant " + productname + " has dropped to " + productinventory;
            var subject = "Low Stock Notification";
            var emailAddress = "email@email.com";
            MailApp.sendEmail(emailAddress, subject, message);
            range.offset(0,1).setValue("notified");
        }
    }
}

谢谢!

2 个答案:

答案 0 :(得分:11)

尝试这样的事情,看看它是否有效:

function onEdit(e) {
    var activeSheet = e.source.getActiveSheet();
    var range = e.range;
    if (activeSheet.getName() !== "Inventory" || e.value !== "notify") return;
    range.setBackgroundColor('red');
    var productname = range.offset(0, -3).getValue();
    var productinventory = range.offset(0, -2).getValue();
    var message = "Product variant " + productname + " has dropped to " + productinventory;
    var subject = "Low Stock Notification";
    var emailAddress = "email@email.com";
    MailApp.sendEmail(emailAddress, subject, message);
    range.offset(0, 1).setValue("notified");
}

现在,如果活动工作表不是“库存”,或者编辑后的值不是“通知”,则脚本将退出。

答案 1 :(得分:2)

我建议您尝试一下:

with