【问题标题】:Google script for google sheets - Range copy paste special 'add'谷歌表格的谷歌脚本 - 范围复制粘贴特殊“添加”
【发布时间】:2019-04-27 04:49:55
【问题描述】:

我真的是脚本新手,我以前在 microsoft office 上工作,它有一个特殊的粘贴“添加”功能,现在对于 google sheet 我真的找不到它。

我将有一个 C2:C102 的源范围和目标在同一张表 D2:D102 我希望脚本(我可以每周手动运行)复制源中的所有范围并将其与 D2 中已经存在的数据相加:D102(仅值)。

这是一个小例子 - Before after

我尝试使用此代码,但它只是替换了值。

function copyCells(){
   var thisSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var SourceSheet = thisSpreadsheet.getSheetByName("test");
  var SourceRange = thisSpreadsheet.getRange("C2:C102");

  var destinationSheet = thisSpreadsheet.getSheetByName("test");
  var destinationRange = destinationSheet.getRange("D2:D102");

   SourceRange.copyTo(destinationRange, {contentsOnly: true}); 
}

任何帮助将不胜感激:)

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    尚未测试代码,但请尝试一下。

    • getValues()获取值
    • 对值求和
    • setValues()复制回值

      function copyCells(){
         const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
         const SourceSheet = spreadsheet.getSheetByName("test");
         const SourceRange = spreadsheet.getRange("C2:C102");
         const SourceValues = SourceRange.getValues();
      
         const destinationSheet = spreadsheet.getSheetByName("test");
         const destinationRange = destinationSheet.getRange("D2:D102");
         const destinationValues = destinationRange.getValues();
      
         for (let i = 0; i < SourceValues.length; i++)
           destinationValues[i][0] = parseFloat(destinationValues[i][0]) + parseFloat(SourceValues[i][0])
      
         destinationRange.setValues(destinationValues);
      }
      

    参考文献

    range.getValues()

    range.setValues()

    【讨论】:

    • 看起来它的工作,我唯一的问题是当我添加十进制数时,例如如果 C2 有 12,5 值它只会添加 12
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多