Google表格自定义菜单能否传递变量以起作用? [英] Can a Google Sheets custom menu pass a variable to function?

查看:86
本文介绍了Google表格自定义菜单能否传递变量以起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Google表格中创建一个菜单项,该菜单项将列出工作目录并提取该用户的电子邮件地址,以供以后在Google表格中处理员工记录.我正在尝试让它像这样工作:

I'm creating a menu item in Google Sheets that will list a work directory and pull the email address for that user, to be later used to process employee records within Google Sheets. I'm trying to get it to work like this:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  var myapp = ui.createMenu('MyApp');
  var pullemp = myapp.addSubMenu(ui.createMenu('Pull Employee')
          .addItem('Nathaniel MacIver', menuItem2('nm@emailaddress.com')));
  myap.addToUi();
}

function menuItem2(email) {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('That email address is '+email);
}

现在,当我打开电子表格时,该项目会立即触发,并在下面得到我想要的结果:

Now, when I open the spreadsheet, The item triggers immediately, and I get the result, below, which is what I want:

但是我希望当我单击菜单中的按钮时触发它.就这样,当我单击菜单按钮时出现错误:

But I want it to trigger when I click the button in my menu. As it is, when I click on my menu button I get the error:

我知道该链接提到功能名称必须是字符串值,但是为什么它会按需要在加载时工作,然后在按下按钮时失败?

I know the link mentions that the function name needs to be a string value, but why would it work onload as I need it to and then fail when I press a button?

推荐答案

使用

.addItem('Nathaniel MacIver', menuItem2('nm@emailaddress.com'))

使用参数'nm@emailaddress.com'调用功能menuItem2.这将导致您看到警报.该函数的返回值是不确定的(因为您不从中返回任何内容).因此,您最终获得了与

the function menuItem2 is called with the parameter 'nm@emailaddress.com'. This results in the alert that you see. The return value of the function is undefined (as you don't return anything from it). So you end up with the same menu item as if it was

.addItem('Nathaniel MacIver', undefined)

这显然不会做任何事情.

which clearly isn't going to do anything.

方法addItem 仅需函数名称,不允许将参数传递给该函数.要完成您想做的事情,您需要为每个人使用单独的功能,每个功能内部都带有一封硬编码的电子邮件.

The method addItem takes only a function name, it does not allow for passing parameters to that function. To do what you want, you'll need separate functions for each person, each with an email hardcoded inside that function.

这篇关于Google表格自定义菜单能否传递变量以起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆