当某些工作表(而不是工作簿的任何工作表)中发生更改时,OnChange会触发



我在工作表文档中有一个名为"Notif Inv"的选项卡,该选项卡还有其他几个选项卡。 这是一个只有 2 行的选项卡,其中第二行使用工作表中另一个选项卡的范围的最新过滤行进行更新。

另一方面,我有这个功能,可以发送电子邮件,从我的"Notif Inv"选项卡的第二行获取数据。

function Email_NewInvs() {
// Get the sheet where the data is, in sheet 'Notif Inv'
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notif Inv");
var startRow = 2; // First row of data to process since there is a header row
var numRows = sheet.getRange(1,5).getValue(); // Number of rows to process is set by a formula which counts rows
// Fetch the range of cells A2:B6 where the emails and messages are
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range to input into the mailing system
var data = dataRange.getValues();
// This processes the emails you want to send
for (i in data) { var row = data[i];
var emailAddress = row[0]; // First column is the email address
var message = row[1]; // Second column is the message
var subject = "Nueva Factura"; // This is the subject of the email
// This parses the data for the email to send
MailApp.sendEmail(emailAddress, subject, message);
}
}

我的目标是在"Notif Inv"选项卡中的第二行自动更改时触发此功能。

我尝试为此脚本使用 onChange 触发器,但它实际上会在所有工作表文档发生任何更改时触发它,这意味着在与此无关的选项卡中所做的更改也是如此。

我还尝试将函数名称更改为onChange(e),但是当在"Notif Inv"选项卡中发生更改时,它没有任何作用。

有什么解决方法吗?

非常感谢

要求:

使用触发器onChange脚本应仅在工作表"Notif Inv"发生更改时运行。


溶液:

将 change 事件传递给函数,并使用工作表getName()来确定正在编辑的工作表,然后根据结果运行if语句。


例:

function Email_NewInvs(e) {
// Get the sheet where the data is, in sheet 'Notif Inv'
var sheet = e.source.getActiveSheet();
if (sheet.getName() === 'Notif Inv') {
var startRow = 2; // First row of data to process since there is a header row
var numRows = sheet.getRange(1,5).getValue(); // Number of rows to process is set by a formula which counts rows
// Fetch the range of cells A2:B6 where the emails and messages are
var dataRange = sheet.getRange(startRow, 1, numRows, 2)
// Fetch values for each row in the Range to input into the mailing system
var data = dataRange.getValues();
// This processes the emails you want to send
for (i in data) { 
var row = data[i];
var emailAddress = row[0]; // First column is the email address
var message = row[1]; // Second column is the message
var subject = "Nueva Factura"; // This is the subject of the email
// This parses the data for the email to send
MailApp.sendEmail(emailAddress, subject, message);
}
}
}

解释:

我们现在将事件对象与您的函数一起使用Email_NewInvs(e)来定义var sheet,以便我们可以检查哪个工作表已更改:

var sheet = e.source.getActiveSheet();

我添加了一个if语句来检查已更改工作表的名称:

if (sheet.getName() === 'Notif Inv') {

因此,现在仅当要更改的工作表的名称与"Notif Inv"匹配时,脚本才会运行。


笔记:

  1. 需要为此脚本设置可安装触发器,以便 它有足够的授权来发送电子邮件。
  2. 您将无法从脚本手动运行此脚本 编辑器,它将在工作表更改时自动运行。

引用:

  1. 事件对象
  2. 可安装触发器

感谢您的回答。 我已经使用了您的代码,但不幸的是它不起作用。 我已经使用 onChange 事件类型为这个函数设置了一个可安装的触发器,但我只看到它的执行......但是没有发送电子邮件。 另一方面,当我在其他选项卡中更改某些内容时,它仍然会发送执行...... :(

最新更新