我正在尝试创建一个脚本,该脚本允许用户将突出显示的单元格区域复制到另一个未打开的Google表格文档中。如果要复制数据的工作表在当前文档中,则可以使它工作,但是我不知道如何将数据复制到其他电子表格中。
我尝试了 openById 或 openbyUrl ,但是我不断收到以下错误消息:
“目标范围和源范围必须在同一电子表格上。”
function copyToDifferentDocument() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// *** Have to figure out how to make the target a different document!!!! ***
var target = SpreadsheetApp.openById("targetsheetIDgoeshere");
/*
Next we need to pick the particular sheets within those spreadsheets.
Let's say your row is on the sheet named "New Stuff", and you have a sheet in the target spreadsheet named "Archive".
*/
var source_sheet = ss.getSheetByName("New Stuff");
var target_sheet = target.getSheetByName("Archive");
// The below makes the highlighted cells the range that will be copied.
var source_range = source_sheet.getActiveRange();
var last_row = target_sheet.getLastRow();
target_sheet.insertRowAfter(last_row);
var target_range = target_sheet.getRange("A"+(last_row+1)+":G"+(last_row+1));
// Take the highlighted rant and put it on the last row of the target sheet.
source_range.copyTo(target_range);
}
我正试图将突出显示的范围复制到其他Google工作表文档中的工作表中。
答案 0 :(得分:0)
如果我的理解是正确的,那么该修改如何?我认为您的情况有两种模式。
在此模式中,仅复制值。请进行如下修改。如果不需要复制格式,则可以使用此格式。
从:target_sheet.insertRowAfter(last_row);
var target_range = target_sheet.getRange("A"+(last_row+1)+":G"+(last_row+1));
// Take the highlighted rant and put it on the last row of the target sheet.
source_range.copyTo(target_range);
至:
var values = source_range.getValues();
target_sheet.getRange(last_row + 1, 1, values.length, values[0].length).setValues(values);
在此模式下,将同时复制值和格式。请进行如下修改。不幸的是,copyTo()
只能将范围复制到同一电子表格上的范围。在您的问题的错误消息中也可以看到这种情况。因此,在此修改中,首先,将工作表复制到目标电子表格。然后,将范围复制。
target_sheet.insertRowAfter(last_row);
var target_range = target_sheet.getRange("A"+(last_row+1)+":G"+(last_row+1));
// Take the highlighted rant and put it on the last row of the target sheet.
source_range.copyTo(target_range);
至:
if (last_row > 0) target_sheet.insertRowAfter(last_row);
var target_range = target_sheet.getRange(last_row + 1, 1);
var copiedsheet = source_sheet.copyTo(target);
copiedsheet.getRange(source_range.getA1Notation()).copyTo(target_range);
target.deleteSheet(copiedsheet);
如果我误解了你的问题,我表示歉意。