我目前正在尝试将一系列单元格从电子表格 A 复制到电子表格 B。在这个范围内,我有一些我正在尝试使用的值和公式的组合。
我尝试使用 .copyTo 方法:
SpreadsheetA.getRange("A:E").copyTo(SpreadsheetB.getRange("A:E"), {contentsOnly:true});
但是这个 .copyto 错误只会在相同电子表格中起作用,如果它们是分开的,则不起作用。我也尝试过使用 .setValues() 和 .setFormulas() 但如果一个接一个地使用,它们似乎会相互覆盖。我需要一个函数,如下所示:
CopyData(SourceSpreadsheet, DestinationSpreadsheet, SourceRange, DestinationRange)
这将根据它们的内容复制公式和值。如果有人有例子,非常感谢!您将成为救星。
答案 0 :(得分:0)
不仅仅是setValues()
和setFormulas()
,我想说的问题是从getValues()和getFormulas()开始的:getValues()
只获取值(包括最终结果)公式),而 getFormulas()
只得到公式,而不是“简单”值。
所以一种选择是设置整个范围的值,然后只用特定单元格的公式替换值:
getValues()
分别获取值和公式
和getFormulas()
。setValues()
设置范围的值。setFormula()
并从
公式数组。像这样:
function copyValuesAndFormulasBetweenSpreadsheets(sourceSpreadsheet, sourceRangeA1Notation, destinationSpreadsheet, destinationRangeA1Notation) {
const values = sourceSpreadsheet.getSheets()[0].getRange(sourceRangeA1Notation).getValues();
const formulas = sourceSpreadsheet.getSheets()[0].getRange(sourceRangeA1Notation).getFormulas();
const range = destinationSpreadsheet.getSheets()[0].getRange(destinationRangeA1Notation);
range.setValues(values);
for (let i = 0; i < formulas.length; i++) {
for (let j = 0; j < formulas[i].length; j++) {
if (formulas[i][j]) {
range.getCell(i+1, j+1).setFormula(formulas[i][j]);
}
}
}
}
这种方法的缺点是,如果有很多公式,您可能需要单独检查多个单元格,这可能需要一些时间,具体取决于范围。
答案 1 :(得分:0)
根据@mshcruz 的评论,我做了一个小小的改进,没有为每个单元格设置 .get/.set:
function copyValuesAndFormulasBetweenSpreadsheets(sourceSpreadsheet, sourceRangeA1Notation, destinationSpreadsheet, destinationRangeA1Notation) {
const values = sourceSpreadsheet.getSheets()[0].getRange(sourceRangeA1Notation).getValues();
const formulas = sourceSpreadsheet.getSheets()[0].getRange(sourceRangeA1Notation).getFormulas();
destinationSpreadsheet.getSheets()[0].getRange(destinationRangeA1Notation).setValues(values);
for (let i = 0; i < formulas.length; i++) {
for (let j = 0; j < formulas[i].length; j++) {
if (formulas[i][j]) {
const cell = range.getCell(i+1, j+1);
cell.setFormula(formulas[i][j]);
}
}
}
}