GAS"您无权调用openById"

use*_*111 10 google-sheets google-apps-script custom-function

问题:当我运行脚本时,Google告诉我," 您无权调用openById. "

我从另一个Google电子表格中复制了一个脚本,并更改​​了target_ssKey变量的单元格引用,并在源电子表格和目标电子表格中创建了适当大小的命名范围.

GAS文档没有说明它可能无法工作的原因:

https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app#openById%28String%29

另一个GAS文档说它应该对我有用,因为我从自定义菜单中调用它:

https://developers.google.com/apps-script/guides/sheets/functions#using_apps_script_services

上面的第二个链接说:

如果您的自定义函数抛出错误消息您没有权限调用X服务.,该服务需要用户授权,因此不能用于自定义功能.

要使用上面列出的服务以外的服务,请创建一个运行Apps脚本功能的自定义菜单,而不是编写自定义功能.从菜单触发的功能将在必要时要求用户进行授权,因此可以使用所有Apps脚本服务.

我尝试将该函数放入"自定义函数"项目,然后放入"附加"项目,但仍然得到相同的错误消息.

关于我做错了什么以及如何使这项工作的任何想法?

这是我的确切代码:

function exportData_SStoSS() {
    //  Get the source data.
    var source_ss = SpreadsheetApp.getActiveSpreadsheet();
    var data = source_ss.getRangeByName("exportData").getValues();

    //  Identify the target.
    var controls_sh = source_ss.getSheetByName("Controls");
    var target_ssKey = controls_sh.getRange('C2').getValue();
    var target_ss = SpreadsheetApp.openById(target_ssKey);

    //  Paste the data to the target.
    target_ss.getRangeByName("importData").setValues(data);
};
Run Code Online (Sandbox Code Playgroud)

小智 22

我可以通过谷歌开发人员的授权指南解决这个问题。

https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes

此条目在 json 文件中是必需的。

 "oauthScopes": [
      "https://www.googleapis.com/auth/spreadsheets.readonly",
      "https://www.googleapis.com/auth/userinfo.email",
      "https://www.googleapis.com/auth/spreadsheets"
  ],
Run Code Online (Sandbox Code Playgroud)

  • 这帮助我解决了我的问题,需要将其抱怨的范围添加到项目根目录中的“appsscript.json”。如果您没有看到此文件,则需要转到“项目设置”(位于左侧导航栏中)并选中“在编辑器中显示“appsscript.json”清单文件”复选框。 (2认同)

小智 9

我发现这张官方说明我相信可以解决造成这个问题的原因.

如果您的函数是自定义函数,可以像工作表本身中的常规电子表格函数一样使用,那么它对事物的访问权限有限,无法打开其他电子表格.

但是,相同的脚本可以从菜单按钮或类似按钮打开其他电子表格.

链接:developers.google.com上的文档


Sco*_*McC 8

我以为我会抛出一个类似的问题,这个问题让我想到了这个问题,我收到了错误You don't have permission to call by openById.在我的情况下,我试图调用translate.gs我从这个示例中复制的函数:

https://developers.google.com/apps-script/quickstart/docs

请注意,在顶部 translate.gs

/**
 * @OnlyCurrentDoc
 *
 * The above comment directs Apps Script to limit the scope of file
 * access for this add-on. It specifies that this add-on will only
 * attempt to read or modify the files in which the add-on is used,
 * and not all of the user's files. The authorization request message
 * presented to users will reflect this limited scope.
 */
Run Code Online (Sandbox Code Playgroud)

这里的罪魁祸首是@OnlyCurrentDoc评论.见这里参考:

https://developers.google.com/apps-script/guides/services/authorization

删除@OnlyCurrentDoc修复此问题对我来说

  • 删除@OnlyCurrentDoc也为我解决了这个问题 (2认同)
  • 好吧,我的应用程序脚本中没有 @OnlyCurrentDoc 标签,但我收到此错误。 (2认同)

use*_*111 2

该方法openById可以从“空白项目”调用,但不能从“表格中的自定义函数”或“Google 表格插件”项目调用。

我认为“空白项目”会创建一个未连接到我的电子表格的项目,但我错了。空白项目已连接到我的电子表格。我尝试使用的其他类型的项目似乎是脚本项目的有限范围版本,无法执行某些 GAS 方法。

  • 这些信息有官方来源吗? (3认同)