Pathead
Pathead

Reputation: 778

How to create time based triggers in Multiple Google Sheets

I would like to install a time based trigger on multiple Google Sheets using Google Apps Scripts and can't figure out how to do so. I know these can be added through the UI but I was hoping to find a programmatic way to do this. I have tried this code:

function initializeTrigger(sheetID){ 
  var sheet = SpreadsheetApp.openById(sheetID);
  ScriptApp.newTrigger('myLibrary.myFunction')
  .forSpreadsheet(sheet)
  .timeBased()
  .atHour(9)
  .everyDays(1)
  .create();
}

function installMultipleTriggers(){
  var sheetList = [sheetID1, sheetID2, sheetID3];

  for (var i = 0; i < sheetList.length; i++)
  {
    initializeTrigger(sheetList[i]);
  }
}

But when I run this I receive the error:

TypeError: Cannot find function timeBased in object SpreadsheetTriggerBuilder.

Which makes sense I guess, because according to the documentation, the SpreadsheetTriggerBuilder class doesn't have a method named timeBased()... Does anyone know how to add time-based triggers to multiple Google Sheets?

Upvotes: 1

Views: 1408

Answers (3)

Suresh Patel
Suresh Patel

Reputation: 1

Access sheets in loop and assign trigger that may be only option

Upvotes: 0

Cooper
Cooper

Reputation: 64042

Create Spreadsheet Triggers Programatically

So I guess the issue here is that you wish to tie the triggers to a spreadsheet. I believe that only way to do that is to create the triggers from a project that is contained by the spreadsheet and you can just use ClockTriggerBuilder.

Upvotes: 0

TheAddonDepot
TheAddonDepot

Reputation: 8964

A time based trigger is independent of a sheet based trigger. Sheet based triggers respond to events that occur on the sheet, for example if you edit a cell.

I would eliminate the forSpreadsheet call in your code snippet, that should resolve your issue.

Upvotes: 3

Related Questions