如何在Google Apps Script函数中同时处理不同单元格的阈值判断?
修改方案
方式一:直接添加独立判断块(适合初学者,直观易懂)
这种方式直接在原有逻辑后新增一个判断块,两个条件独立生效,满足各自阈值时都会发送告警邮件:
function CheckSales() { // 统一获取"non inventory"工作表,避免重复调用 const nonInventorySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("non inventory"); // 获取C28和C29的数值 const salesC28 = nonInventorySheet.getRange("C28").getValue(); const salesC29 = nonInventorySheet.getRange("C29").getValue(); // 统一获取收件邮箱(也可以保留原代码写死的方式,这里改成从data表L5读取更灵活) const emailAddress = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data").getRange("L5").getValue(); // 检查C28是否低于200 if (salesC28 < 200) { const message = `Przygotuj zapotrzebowanie! Inwentarz w komórce C28 spadł do wartości ${salesC28}`; const subject = "Low Inventory Alert"; MailApp.sendEmail(emailAddress, subject, message); } // 检查C29是否低于250 if (salesC29 < 250) { const message = `Przygotuj zapotrzebowanie! Inwentarz w komórce C29 spadł do wartości ${salesC29}`; const subject = "Low Inventory Alert"; MailApp.sendEmail(emailAddress, subject, message); } }
方式二:封装重复逻辑(更简洁,便于后续扩展)
如果以后还要添加更多单元格的检查,可以把发送邮件的逻辑封装成独立函数,减少代码重复:
function CheckSales() { // 统一获取谷歌表格实例和工作表 const ss = SpreadsheetApp.getActiveSpreadsheet(); const nonInventorySheet = ss.getSheetByName("non inventory"); const emailAddress = ss.getSheetByName("data").getRange("L5").getValue(); // 封装发送告警邮件的函数 function sendInventoryAlert(cellName, currentValue, threshold) { const message = `Przygotuj zapotrzebowanie! Inwentarz w komórce ${cellName} spadł do wartości ${currentValue} (próg alertu: ${threshold})`; const subject = "Low Inventory Alert"; MailApp.sendEmail(emailAddress, subject, message); } // 检查C28 const c28Value = nonInventorySheet.getRange("C28").getValue(); if (c28Value < 200) { sendInventoryAlert("C28", c28Value, 200); } // 检查C29 const c29Value = nonInventorySheet.getRange("C29").getValue(); if (c29Value < 250) { sendInventoryAlert("C29", c29Value, 250); } }
关键说明
- 两个判断用独立的
if语句而非else if,这样当C28和C29同时满足条件时,会分别发送两封告警邮件,实现“同时生效”的需求。 - 把重复的工作表、邮箱获取逻辑提到函数开头,避免多次调用相同方法,提升代码效率。
- 邮件消息中添加了单元格名称,方便收件人快速定位对应的库存数据。
内容的提问来源于stack exchange,提问作者Damian Lewandowski
相关产品推荐
相关产品推荐

