【问题标题】:Google Apps Script: Copy and Paste Formulas OnlyGoogle Apps 脚本:仅复制和粘贴公式
【发布时间】:2017-05-23 09:24:23
【问题描述】:

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

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

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

CopyFormulasToRange 很遗憾不存在。

【问题讨论】:

    标签: javascript google-apps-script google-sheets


    【解决方案1】:

    使用 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);
    

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

    【讨论】:

      【解决方案2】:

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

      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
      }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2018-10-22
      • 2017-03-28
      相关资源
      最近更新 更多