Google 表格“您无权调用 appendRow”

Cha*_*man 8 javascript google-apps-script google-spreadsheet-api

function myFunction() {
    var url = 'https://api.github.com/users/chaimf90/repos'
    var response = UrlFetchApp.fetch(url);
    var json = response.getContentText();
    var data = JSON.parse(json)
    var sheet = SpreadsheetApp.getActiveSheet();
    sheet.appendRow(['Repo Name', data[0].name]);
}
Run Code Online (Sandbox Code Playgroud)

当我从脚本编辑器执行此函数时,它会按预期运行,但是当我尝试通过调用在工作表本身中调用此函数时=myFunction(),我收到一条错误消息,指出我无权调用appendRow.

为什么我可以从脚本编辑器而不是从工作表本身调用这个函数?

小智 10

我有同样的问题。解决方案似乎是创建一个运行 Apps 脚本函数的自定义菜单,而不是编写自定义函数并从电子表格中的单元格调用它。

从菜单触发的功能将在必要时要求用户授权,因此可以使用所有 Apps 脚本服务。我在这里学到了这个。

例子:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Custom Menu')
      .addItem('Run My Function', 'myFunction')
  .addToUi();
}

function myFunction() {
  SpreadsheetApp.getUi()
     .alert('Running My Function');
}
Run Code Online (Sandbox Code Playgroud)

编写并保存此代码后:

  1. 关闭并重新打开您的 Google 表格文档。
  2. 几秒钟后,一个新菜单“我的自定义菜单”将出现在顶部,在文件、编辑、查看、...、帮助旁边。
  3. 单击“我的自定义菜单”,然后单击“运行我的函数”以调用函数 myFunction。