Google Apps 脚本:仅复制和粘贴公式

Dom*_*Dom 3 javascript google-sheets google-apps-script

我只需要使用 Google Apps 脚本在电子表格中复制和粘贴公式

var range = activeSheet.getRange(targetRow-1, 1, 1, activeSheet.getLastColumn());
range.copyTo(activeSheet.getRange(targetRow, 1, 1, activeSheet.getLastColumn()), {contentsOnly:false});
Run Code Online (Sandbox Code Playgroud)

这给了我完整的信息,包括公式和数据。但是,我只想复制公式(没有数据)。

CopyFormulasToRange 不幸的是不存在。

Mar*_*ird 9

使用 getFormulasR1C1 和 setFormulasR1C1 复制公式并保留相对引用。例如:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");

  var currentRow = sheet.getLastRow();

  var sourceRange = sheet.getRange(currentRow, 3, 1, 4);
  var sourceFormulas = sourceRange.getFormulasR1C1();

  currentRow++;

  var targetRange = sheet.getRange(currentRow, 3, 1, 4);
  targetRange.setFormulasR1C1(sourceFormulas);
Run Code Online (Sandbox Code Playgroud)

https://developers.google.com/apps-script/reference/spreadsheet/range#getformular1c1 https://developers.google.com/apps-script/reference/spreadsheet/range#setformulasr1c1formulas


Ala*_*lls 6

以下函数将仅复制公式。它具有用于开始获取公式的行和列的用户设置。

function copyFormulas() {
  var activeSheet,numberOfSourceColumnsToGet,sourceColumnStart,sourceFormulas,sourceRange,
      sourceRowStart,targetColumn,targetRange,targetRowStart;

  //USER INPUT

  sourceRowStart = 1; //Row to start getting formulas from
  sourceColumnStart = 2; //Column to start getting formulas from
  numberOfSourceColumnsToGet = 1; //Number of columns to get formulas from

  targetRowStart = 1; //Row to start copying formulas to
  targetColumn = 3; //Column to start copying formulas to

  //END OF USER INPUT

  activeSheet = SpreadsheetApp.getActiveSheet();
  sourceRange = activeSheet.getRange(sourceRowStart, sourceColumnStart, activeSheet.getLastRow(), numberOfSourceColumnsToGet);

  sourceFormulas = sourceRange.getFormulas();//Get only formulas from the source range

  targetRange = activeSheet.getRange(targetRowStart,targetColumn,sourceFormulas.length,sourceFormulas[0].length);

  targetRange.setFormulas(sourceFormulas);//Copy the formulas to the target range
}
Run Code Online (Sandbox Code Playgroud)

  • 似乎公式没有扩展;就像excel的“下拉公式”一样 (2认同)
  • 此函数不会更新复制的公式以引用新行中的单元格值。所有引用保持不变,引用复制公式的行中的单元格。也许在某些情况下您需要这样做,但在我看来,更常见的情况是希望新公式引用新行单元格中的值。我添加了一个答案,在仅复制包含公式的单元格时执行此操作。 (2认同)