JKC
JKC

Reputation: 109

Unexpected error while creating an installable trigger for google sheets

I want to create an installable trigger for googlesheets and here is the Apps Script code that creates it:

function setTrigger() {
  var ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger("myFunction").forSpreadsheet(ss).onEdit().create();
}

function myFunction() {
  Logger.log('x');
}

When I run the function setTrigger() from Apps Script, I get the exception:

Exception: Unexpected error while getting the method or property forSpreadsheet on object ScriptApp.TriggerBuilder.setTrigger

Upvotes: 1

Views: 140

Answers (1)

Marios
Marios

Reputation: 27348

Explanation:

The issue is you are executing this script from a standalone script.

In this case, there is not active spreadsheet and therefore you need to change:

var ss = SpreadsheetApp.getActive()

to:

var ss = SpreadsheetApp.openById('Spreadsheet_ID');

where 'Spreadsheet_ID' is the id of your spreadsheet file*.

Another option would be to go the target spreadsheet file and use your current solution. To do that, open Tools => Script editor and your script will be bound to the spreadsheet file.

Solution:

function setTrigger() {
  var ss = SpreadsheetApp.openById('Spreadsheet_ID');
  ScriptApp.newTrigger("myFunction").forSpreadsheet(ss).onEdit().create();
}

function myFunction() {
  Logger.log('x');
}

*For example, the spreadsheet ID in the URL https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 is "abc1234567".

Upvotes: 1

Related Questions