1
votes

I have a large number of simple spreadsheets (each shared with a different agent), and one large "management" spreadsheet that is used to interface with all of them.

When adding a new agent, I use a script (bound to the management-spreadsheet), to copy and rename a template-spreadsheet. The template-spreadsheet has an onEdit trigger which is not copied to the new instance. When I try to add it after copying (see script below), it is added to the management-spreadsheet instead of the new spreadsheet.

function NewAgent(filename) {
  // create new spreadsheet from template
  var folder = DriveApp.getFoldersByName(AgentFolder).next();
  var tmplt = DriveApp.getFilesByName(AgentTemplate);
  var newfile = tmplt.next().makeCopy(filename, folder );
  var newspread = SpreadsheetApp.openById( newfile.getId() );

  ScriptApp.newTrigger("MyFunction").forSpreadsheet(newspread).onEdit().create();

  SpreadsheetApp.flush();
}

The function MyFunction is bound to the template (and also appears in the script bound to the new spreadsheet). The function NewAgent is, as stated bound to the management script. The result is that the trigger is added to the management-spreadsheet...

ideas?

Thanks

2

2 Answers

0
votes

Try this. The issue might be your were referring to the "newfile" variable.

    function NewAgent(filename) {
      // create new spreadsheet from template
      var folder = DriveApp.getFoldersByName(AgentFolder).next();
      var tmplt = DriveApp.getFilesByName(AgentTemplate);
      var newfile = tmplt.next().makeCopy(filename, folder );
      var newspread = SpreadsheetApp.openById( DriveApp.getFilesByName(        filename ) );
    }

ScriptApp.newTrigger("MyFunction").forSpreadsheet(newspread).onEdit().create();

SpreadsheetApp.flush(); }

0
votes

The problem is that forSpreadsheet() accepts a Spreadsheet ID as an argument, and your sending the file, remove SpreadsheetApp.openById( from the code and it should be fine:

var newspread = newfile.getId();