问题描述:

I have a doubt in how to implement (and call) an installable onOpen() trigger. I tried the method bellow, but it didn't work. What I'm doing wrong?

Thanks for any help!

 var ss = SpreadsheetApp.getActiveSpreadsheet();

var myOnEdit = ScriptApp.newTrigger("installedOnOpen")

.forSpreadsheet(ss.getId())

.onOpen()

.create();

function installedOnOpen() {

var menuEntries = [

{name: My function menu name", functionName: "someFunction"}

];

ss.addMenu("My personalized menu", menuEntries);

}

网友答案:

Hello craft Apprentice,

On the code you posted:

 var myOnEdit = ScriptApp.newTrigger("installedOnOpen")
                           .forSpreadsheet(ss.getId())
                           .onOpen()
                           .create();  

is not a function and it will never be called. If you want to launch this code you must put it in a function:

function addOnOpenTrigger(){
  var sheet = SpreadsheetApp.getActive();
 ScriptApp.newTrigger("installedOnOpen").forSpreadsheet(sheet).onOpen().create();  
}

then on your function installedOnOpen() you forgot a " just after {name: to start the name of your function.
here the full code that will work:

var ss = SpreadsheetApp.getActiveSpreadsheet();

function addOnOpenTrigger(){
  var sheet = SpreadsheetApp.getActive();
 ScriptApp.newTrigger("installedOnOpen").forSpreadsheet(sheet).onOpen().create();  
}

function installedOnOpen() {
  var menuEntries = [
                     {name: "My function menu name", functionName: "someFunction"}
                    ];
  ss.addMenu("My personalized menu", menuEntries);
}

From the script editor you must launch the function addOnOpenTrigger() (it will ask you the authorisation to launch the script when you are not there) and now if you close and open again your spreadsheet you should see your new menu "My personalized menu".

But if you only want to add a custom menu entry to your spreadsheet the best way is to use the special function onOpen() that will be launch at the opening of the spreadsheet (if you don't put anything in it that require special authorisation). Just like in the Google spreadsheet script template that you can get when you create a new script.
Hope it helped you.
Harold

相关阅读:
Top