Reputation: 22316
Can anybody see anything wrong in this code
// make new ssheet
var payablesNewDoc=SpreadsheetApp.getActiveSpreadsheet().copy(newName); // NB undocumented function
// Create onEdit trigger for the new Spreadsheet
var onEditTrigger = ScriptApp.newTrigger("onChange")
.forSpreadsheet(payablesNewDoc)
.onEdit()
.create();
Logger.log(onEditTrigger.getHandlerFunction()); // logs "onChange"
Logger.log(onEditTrigger.getEventType()); // logs "ON_EDIT"
It runs without error, and the two log messages seem to indicate that the trigger was created. However when I open the new spreadsheet and make an edit, nothing is fired and the script editor doesn't show any declared triggers.
Upvotes: 1
Views: 1059
Reputation: 4034
because it seems in this instance you are making a copy of the host Sheet and script, the onEdit
can be added as a simple trigger within the template script, i.e. a function so defined: function onEdit() { // do stuff }
.
This function will be copied along with the Spreadsheet itself.
function onEdit() {
// This function being present will automatically add an onEdit trigger
// It can act as a parent for calling any other functions
// e.g. onChange() as per your example
}
One improvement you could make if you are likely to have many copies of the same script floating about you can call a handler function hosted in a library elsewhere to keep your triggered code in one place. If you attach the external script as a Library with development mode turned on, this Library will also be attached to any copies you make to the original Spreadsheet. This will allow you amend the triggered code without having to open all the copies
Make a standalone GS script with a handler function that will replicate the functions you originally wished to trigger, you will need to pass the active sheet by Id thusly:
function editFunction(event) {
try {
var range = event.source.getActiveSheet().getActiveSelection();
return "cells " + range.getA1Notation() + \
" changed to " + range.getValues().toString() + \
" in \"" + event.source.getName() + \
"\" by " + Session.getEffectiveUser();
} catch (err) {
return err;
}
}
then in your template Spreadsheet add the external script as a library (e.g. named EditLibrary
).
within your simple onEdit()
function simply call the Library function instead of anything inline; passing event details as a parameter.
function onEdit() {
Browser.msgBox(EditLibrary.editFunction(eventObject));
}
that should do what you need with no need to use the triggerBuilder and allowing you amend your code later.
Upvotes: 1
Reputation: 22316
On this thread Is there any way to install an "on edit trigger" in another google docs spreadsheet?
I read "While it is possible to add an onEdit trigger for another spreadsheet, the trigger will always belong to the script that created it, and can only run functions within the script that created it. – Eric Koleda Jun 30 at 0:05"
Perhaps this is the explanation?
Upvotes: 1