您无权使用 copyTo

You do not have permission to use copyTo

我正在尝试将范围从一个 sheet 复制到另一个范围( 同时保留公式 )。我使用 copyTo:

编写了一个简单的脚本
function copyRangeAcrossSheets(source_sheet,source_range,target_sheet,target_range) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source_sheet = spreadsheet.getSheetByName(source_sheet);
  var target_sheet = spreadsheet.getSheetByName(target_sheet);
  var source_range = source_sheet.getRange(source_range);
  var target_range = target_sheet.getRange(target_range);
  source_range.copyTo(target_range);
}

我这样称呼:

=copyRangeAcrossSheets("TEST_source","A1:A3","TEST_target","A1:A3")

我收到以下错误:

You do not have the permission to call copyTo

我四处挖掘了一下,发现 。但是我在这里修改同一个文件。

问题 1:为什么 copyTo 在这里失败了?

问题 2:如何在不定义可安装触发器的情况下解决该问题?(我只想在保留公式的同时复制范围)

为什么会失败?

您不能修改其他任何需要通过自定义函数授权的文档。原因是您的功能是以匿名用户身份执行的,无法获得必要的授权来编辑您的其他工作表或文档。

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

这个片段是您的专属:

Spreadsheet: Read only (can use most get*() methods, but not set*()). Cannot open other spreadsheets (SpreadsheetApp.openById() or SpreadsheetApp.openByUrl()).

还有:

If your custom function throws the error message "You do not have permission to call X service.", the service requires user authorization and thus cannot be used in a custom function.

如何解决这个问题?

编写通过触发器或手动执行的 Apps 脚本函数,您可以使用 onEditonChange 触发器,或基于时间的触发器。您甚至可以在需要时手动 运行 Apps 脚本 IDE 中的函数。这是 Apps 脚本的预期行为。

不确定您的数据是否永久保存在源电子表格中,但您始终可以使用内置的 IMPORTRANGE() 函数。语法是:

=IMPORTRANGE("SPREADSHEET_ID","SOURCE_SHEET!RANGE_START:RANGE_END")

其中 SPREADSHEET_ID 是您正在处理的文件的 ID。