【问题标题】:Copy and paste values without duplicates in spredsheets在电子表格中复制和粘贴不重复的值
【发布时间】:2021-12-19 15:01:47
【问题描述】:

我只想将值(不是公式)从源范围复制并粘贴到目标,而没有重复项(某些值已经在目标范围内)。我尝试在网上按照几个教程从复制粘贴部分开始(甚至不是唯一条件),但不断收到错误“参数(字符串、数字、数字、数字)与 SpreadsheetApp 的方法签名不匹配.Spreadsheet.getRange ..."。不知道为什么,因为我使用的是相同的代码。还尝试了使用 copyTo 而不是 setValues 的方法,但得到了同样的错误。

function paste() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var source = spreadsheet.getDataRange();
  var sourceValues = source.getValues();

  var rowCount = sourceValues.length;
  var columnCount = sourceValues[0].length;

  var target = spreadsheet.getRange(1,4, rowCount, columnCount);
  target.setValues(sourceValues);
}

这是我想要得到的sample spreadsheet。 我知道使用公式会更容易,但问题是我在 Source 中的数据是动态的,因为它来自 ImportXML,所以有时提取的数据会消失,这就是为什么我想在它们丢失之前只粘贴值。

【问题讨论】:

  • 仅使用您在问题中显示的代码显示错误。见minimal reproducible example
  • 这种类型的问题通常很容易解决,方法是使用调试器单步执行脚本并查看每个中间步骤的结果。在某些情况下,您可能必须创建中间变量才能在调试器中查看数据。一旦你学会了如何使用调试器,你会发现对这些问题的需求大大减少了。学习如何编码需要学习如何调试。

标签: google-apps-script google-sheets spreadsheet copy-paste


【解决方案1】:

使用filter(),像这样:

function appendA2bToD2e() {
  const ss = SpreadsheetApp.getActive();
  const source = ss.getRange('Sheet1!A2:B');
  const target = ss.getRange('Sheet1!D2:E');
  appendUniquesToRange_(source, target);
}

function appendUniquesToRange_(sourceRange, targetRange) {
  const dataToAppend = sourceRange.getValues();
  const existingData = targetRange.getValues();
  const newData = existingData
    .concat(dataToAppend)
    .filter((row, rowIndex, array) =>
      array
        .map(tuple => tuple[0])
        .indexOf(row[0]) === rowIndex && row[0] !== ''
    );
  targetRange
    .clearContent()
    .offset(0, 0, newData.length, newData[0].length)
    .setValues(newData);
}

【讨论】:

  • 谢谢你,就像一个魅力!我会调查你使用的方法
  • 还有一个问题。如果我想获得一个与 ex 不同的 collums 范围的源。 (A,C,D)(但跳过 B)。我该怎么做?尝试了我在另一个问题中使用 RangeList 阅读的内容,然后使用拼接,但不能真正使它们工作。谢谢
  • 使用const dataToAppend = sourceRange.getValues().map(row => [row[0], row[2], row[3]]); 或类似名称。请仅询问one question per post
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多