I created an installable trigger in a standalone script.
When I change something in the target spreadsheet, nothing happens. I don't get to a brekpoint in onEdit.
So how do I set up the trigger and onEdit to detect Edits?
ScriptApp.newTrigger('myOnEdit'){
.forSpreadsheet('1wfcYwChzLmbqxoXoSZUrXgZJIVbtEyNUIpfxmJihAcY')
.onEdit()
.create();
)
function onEdit(e){
// Set a comment on the edited cell to indicate when it was changed.
var range = e.range;
var ct = e.changeType
var ov=e.oldValue
var nv =e.value
var sc=e.triggerUid
range.setNote('Last modified: ' + new Date());
}
onEdit is a reserved function name to be used for on edit simple trigger. It should not be used for functions that will be called by an installable triggers as this could cause undesired effects as executing the function twice by a single event.
The installable trigger is being created to call a function named myOnEdit. In order to make it works your script should have a function named myOnEdit.
Related
In google sheets, I am trying to get one data to copy from one sheet to another.
I have this code which is working however I would like it to run onEdit when changing cell E4 in Googlesheet1. I am new at this and doesn't seem to get it to quite work with the solutions I found online.
function ExportRange() {
var destination = SpreadsheetApp.openById('googlesheet1');
var destinationSheet = destination.getActiveSheet();
var destinationCell = destinationSheet.getRange("AC3");
var cellData = '=IMPORTRANGE("https://docs.google.com/spreadsheets/googlesheet2", "AE10:AE9697")';
destinationCell.setValue(cellData);
}
Chose between a simple and installable onEdit trigger, depending on your requirements
For most applciaitons a simple onEdit trigger is sufficient, to use it you just need to rename your function ExportRange() to onEdit()
Take advantage of event objetcs that give you informaiton about the event that fired the trigger
So, the trigger onEdit can give you among others information about the event range - that is the range that has been edited
Now you can implement an if statement to specify that the rest of the funciton shall only be run if the event range and the corresponding sheet are as required
Sample:
function onEdit(event) {
var range = event.range;
var sheet = range.getSheet();
if(range.getA1Notation() == "E4" && sheet.getName() == "Googlesheet1"){
var destination = SpreadsheetApp.openById('googlesheet1');
var destinationSheet = destination.getActiveSheet();
var destinationCell = destinationSheet.getRange("AC3");
var cellData = '=IMPORTRANGE("https://docs.google.com/spreadsheets/googlesheet2", "AE10:AE9697")';
destinationCell.setValue(cellData);
}
}
Please note that this function can only be fired by the trigger in
case of an edit. If you try to run it manually, it will give you an
error because event (and thus event.range) will be undefined if
the funciton was not called by an edit event.
I have a script which uses googlesheets, I am new to this also, there the trigger onOpen() and when the sheet is opened it runs whats inside it, however I wanted to run a function even when sheet is not opened. Do I need a trigger to do this? What should I use to do this?
I tried:
OnCreate
Installable
OnEdit
I want to create a time-based trigger will the script run, even if the sheet is not open and/or even if I'm not logged in to Sheets.
I tried:
function onOpen() {
// Trigger every 10 minutes.
ScriptApp.newTrigger('myFunc') //Run Update All Sheets
.timeBased()
.everyMinutes(10)
.create();
}
and outside the script. I wonder which of these works on background.
// Trigger every 10 minutes.
ScriptApp.newTrigger('myFunc') //Run Update All Sheets
.timeBased()
.everyMinutes(10)
.create();
function onOpen() {
}
It is possible to add a trigger programmatically.
https://developers.google.com/apps-script/guides/triggers/installable
Managing triggers programmatically
You can also create and delete triggers programmatically with the Script service. Start by calling ScriptApp.newTrigger(functionName), which returns a TriggerBuilder.
The following example shows how to create two time-driven triggers—one that fires every 6 hours, and one that fires every Monday at 9 a.m. (in the time zone that your script is set to).
triggers/triggers.gsView on GitHub
/**
* Creates two time-driven triggers.
*/
function createTimeDrivenTriggers() {
// Trigger every 6 hours.
ScriptApp.newTrigger('myFunction')
.timeBased()
.everyHours(6)
.create();
// Trigger every Monday at 09:00.
ScriptApp.newTrigger('myFunction')
.timeBased()
.onWeekDay(ScriptApp.WeekDay.MONDAY)
.atHour(9)
.create();
}
This next example shows how to create an installable open trigger for a spreadsheet. Note that, unlike for a simple onOpen() trigger, the script for the installable trigger does not need to be bound to the spreadsheet. To create this trigger from a standalone script, simply replace SpreadsheetApp.getActive() with a call to SpreadsheetApp.openById(id).
triggers/triggers.gsView on GitHub
/**
* Creates a trigger for when a spreadsheet opens.
*/
function createSpreadsheetOpenTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('myFunction')
.forSpreadsheet(ss)
.onOpen()
.create();
}
To programmatically modify an existing installable trigger, you must delete it and create a new one. If you have previously stored the ID of a trigger, you can delete it by passing the ID as an argument to the function below.
triggers/triggers.gsView on GitHub
/**
* Deletes a trigger.
* #param {string} triggerId The Trigger ID.
*/
function deleteTrigger(triggerId) {
// Loop over all triggers.
var allTriggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < allTriggers.length; i++) {
// If the current trigger is the correct one, delete it.
if (allTriggers[i].getUniqueId() === triggerId) {
ScriptApp.deleteTrigger(allTriggers[i]);
break;
}
}
}
Open your google sheet
Click Tools
Click Script Editor
Make a function. Example Birth day greeting every day is shown below
function hbd_mail() { //birth day mail daily 7 am from hrd login
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Emp");
var today=new Date();
lastRow = sheet.getLastRow();
var values = sheet.getRange('A:T').getValues();
for (i=1;i<lastRow;i++){
if (values[i][14]=="") {} else {
if ( Utilities.formatDate( values[i][14] ,"GMT+05:30", "dd-MMM") == Utilities.formatDate( today ,"GMT+05:30", "dd-MMM") && values[i][18]=="Yes" ) {
var message = 'Dear '+ values[i][1]+',\n\nMegawin Collective wishes you a very happy birth day ('+ Utilities.formatDate( values[i][14] ,"GMT+05:30", "dd-MMM")+ ').\n\nHRD Megawin Switchgear Pvt Ltd';
var subject = "Happy Birth Day "+values[i][1];
if (values[i][7]=="") {} else {GmailApp.sendEmail(values[i][7], subject, message);}
}//if
}
}//for
}
Save the script
Click the Clock in the menu
It will ask you the function name - select the above function
Then select time based
Clcik every hour / day / week etc
Save it.
Now the function will run automatically from google server (at the frequency selected by you) without your having to do anything.
It is pretty simple.
ERROR : You do not have permission to call ScriptApp.newTrigger. Required permissions: https://www.googleapis.com/auth/script.scriptapp.
Having permission problem to create time based trigger
function onEdit(e){
var sheetName = e.range.getSheet().getName()
if(sheetName == "Config")
{
if(e.range.getRow()==2 && e.range.getColumn()==1){
createSpreadsheetOpenTrigger()
}
}
}
function createSpreadsheetOpenTrigger() {
Logger.log("hello")
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger('myFunction')
.forSpreadsheet(ss)
.onOpen()
.create();
}
For Simple Triggers, just running the script within the App Script Web IDE is enough and should prompt you with an authentication popup: Simple Auth Steps.
However, to programmatically create new Triggers you need to make sure the onEdit Trigger is Installable! This gives you increased permissions to do what you need.
We need to open up the dev console to set up an installable trigger.
We need to create a new trigger tied to our function. For installable triggers, it is best not to use the default simple trigger onEdit() function name.
Done! We should be able to run our functions based on triggers with increased permission scopes.
I have a container-bound script attached to a Google Sheet for which I've manually added an On edit installable trigger. I'm using an installable trigger rather than a simple trigger because I want the script to run from the sheet owner's account (my account) no matter who the user is who made the edit. The script is as follows:
function checkTimecardRange() {
var activeSS = SpreadsheetApp.getActiveSpreadsheet();
var activeSheet = activeSS.getActiveSheet();
var cell = sheet.getActiveCell();
var row = cell.getRow();
var approvalTimestamp = activeSheet.getRange("V" + row);
var timecardRange = activeSheet.getRange("A" + row + ":V" + row);
if(timecardRange.isBlank()==false) {
lockTimecardRange(timecardRange, row);
}
}
function lockTimecardRange(timecardRange, row) {
var protection = timecardRange.protect().setDescription('Timecard Row' + row);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
It works fine when I run it manually, but the On edit trigger that I set up for it will not fire. I changed the trigger to a test script:
function log(){
console.log("Hello worlds");
}
and that doesn't fire either. Any assistance in getting the onEdit installable trigger to fire would be greatly appreciated. The edits based on which I expect the trigger to fire are manual edits (at this point I'm just typing in random values) and they are made from the account that owns the sheet and created the scripts.
Well, it turns out that it was a glitch on Google's side. All I had to do was delete the trigger, save, then re-add the trigger without any changes, and everything worked just fine. Go figure.
I'm trying to create a script in Google Sheets that will send me an automated email every time that a value within a given column ("Column H") drops below a certain threshold. I've currently got the following script written, which includes an installable onEdit trigger. However, the script is not running when the spreadsheet is edited:
function StationeryEdited(e){
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getRange(2, 8, 200, 1).getValues();
var newValue = e.value;
if (newValue < "10"){
MailApp.sendEmail("test#test.co", "TEST", "TEST");
}
function createSpreadsheetEditTrigger(){
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger(StationeryEdited)
.forSpreadsheet(ss)
.onEdit()
.create();
}
}
Have you tried putting function name in quotation marks like this?
ScriptApp.newTrigger('StationeryEdited')
Also, you can simply go to Edit -> Current project triggers and configure the trigger for your function manually select the following options for the 'StationeryEdited' function
Try this and set the installable trigger through the script editor:
function onEdit(e) {
var editColumn=e.range.getSheet().getActiveCell().getColumn()
if(editColumn==8 && e.value>10){
MailApp.sendEmail("test#test.co", "TEST", "TEST");
}}