首页 > 解决方案 > Google 工作表:将工作表复制到其他电子表格时出错

问题描述

我正在尝试使用此代码将工作表复制到其他电子表格中。但是,有错误:[例外:指定的工作表必须是电子表格的一部分]

function copy_to_A() {
  
 var source = SpreadsheetApp.getActiveSpreadsheet();
 var destination = SpreadsheetApp.openById(Bestwise_id);
 var tempsheet = source.getSheetByName('Bestwise-tocopy');

 destination.insertSheet('New Sheet Name', 0, {template: tempsheet});
}

标签: google-apps-scriptgoogle-sheetsgoogle-sheets-api

解决方案


问题和解决方法:

不幸的是,似乎当源工作表的电子表格与目标电子表格不同时,insertSheet不能用于其他电子表格。这似乎是当前的规范。那么当你想使用时destination.insertSheet('New Sheet Name', 0, {template: tempsheet});,下面的解决方法怎么样?此解决方法的流程如下。

  1. 将工作tempsheet表从源电子表格复制到目标电子表格。
  2. 使用insertSheet('New Sheet Name', 0, {template: tempsheet}),使用复制的纸张。
  3. 删除复制的工作表。

当这个流程反映到您的脚本时,它变成如下。

修改后的脚本:

function copy_to_A() {
  var source = SpreadsheetApp.getActiveSpreadsheet();
  var destination = SpreadsheetApp.openById(Bestwise_id);
  var tempsheet = source.getSheetByName('Bestwise-tocopy');
  
  // 1. Copy `tempsheet` sheet from source Spreadsheet to destination Spreadsheet.
  var copiedSheet = tempsheet.copyTo(destination);
  
  // 2. Using `insertSheet('New Sheet Name', 0, {template: tempsheet})`, the copied sheet is used.
  destination.insertSheet('New Sheet Name', 0, { template: copiedSheet });
  
  // 3. Delete the copied sheet.
  destination.deleteSheet(copiedSheet);
}

参考:


推荐阅读