Home > Blockchain >  Copy and paste values without duplicates in spredsheets
Copy and paste values without duplicates in spredsheets

Time:12-21

I wanna copy and paste only the values (not formula) from source range to target without the duplicates (some values that are alredy in target range). I tried following a couple of tutorials online to start with the copy-paste part (not even the unique conditional) but keep on getting the error "the parameters (String,number,number,number) don't match the method signature for SpreadsheetApp.Spreadsheet.getRange ... ". Don't really know why, since I'm using the same code. Also tried something with copyTo instead of setValues but get the same error.

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);
}

Here's a sample spreadsheet of what I'd like to get. I know it would be easier with formula, but the thing is my data in Source is dynamic because it's coming from an ImportXML so sometimes the extracted data just disappears, which is why I wanna paste just values when I get them before they goes missing.

CodePudding user response:

Use filter(), like this:

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);
}
  • Related