我有一个脚本,在编辑时从一个工作表中获取数据,并将最近添加的数据放入ScriptDb。
当我实际打开工作表并进行编辑时,onEdit()
触发器被成功触发。
但是,此表是通过脚本以编程方式编辑的。是onEdit()
能够火基于编辑的脚本?我没能让它这样做。
onEdit()
触发触发的脚本为:
function sheetWasEdited(event) {
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
var lastRowValues = sheet.getRange(lastRow, 2, 1, 2).getValues()[0];
CgcEmailDatabase.addEmail(now=lastRowValues[0].toString(), email=lastRowValues[1].toString());
}
onEdit触发器旨在在实际用户编辑电子表格时工作,如果最新的是同一项目的一部分,则您描述的用例应该很容易通过从其他函数调用sheetWasEdited()
函数来实现。
如果更改来自另一个项目(另一个电子表格或web应用程序),那么它将变得非常难以到位。(如果这是你的用例,请告诉我们)
编辑您的评论:
这个想法是监视工作表的长度,保持值在某处(例如在脚本属性中),并在添加一行时调用函数。
这个小代码应该做的伎俩,你应该设置一个时间触发器调用lookatsheet()
一次在一段时间,这取决于你需要多快的反应…我觉得每小时或每30分钟应该不会太多,你决定吧。
function lookatsheet(){
var ss = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxx');// the ID of the SS you want to look at
var sh = ss.getSheets()[0];// first sheet
var lastrow = sh.getLastRow();
var formertest = ScriptProperties.getProperty('lastTest');// recover the value from the last test (will need to get called once to initiate a valid value)
if (formertest < lastrow){
sheetWasEdited(lastrow);// call your function with lastRow as parameter
ScriptProperties.setProperties({'lastTest': lastrow}, true); // store for next time
}
}
function sheetWasEdited(row) { // modified to work with the other function
var sheet = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxx').getSheets()[0]
var lastRowValues = sheet.getRange(row, 2, 1, 2).getValues()[0];
CgcEmailDatabase.addEmail(now=lastRowValues[0].toString(), email=lastRowValues[1].toString());
}
注意:在第一次运行时注释邮件调用可能有用,以避免发送邮件(只是为了初始化脚本属性)