Google-sheets – Check if value exists before copy-paste

google sheetsgoogle-apps-script

Can someone help please as I am new to Google Scripts.

I have this simple code that copies values from one sheet to another

function copyrevision() {
  var ss = SpreadsheetApp.getActiveSpreadsheet ();
  var destSheet = ss.getSheetByName("Fallas Tecnicas");

  //DATE
  var source = ss.getRange ("D4");
  var destRange = destSheet.getRange(destSheet.getLastRow()+1,1);
  source.copyTo (destRange, {contentsOnly: true});

  //REPORT NUMBER
  var source2 = ss.getRange ("C4");
  var destRange = destSheet.getRange(destSheet.getLastRow(),2);
  source2.copyTo (destRange, {contentsOnly: true});

  //OBSERVACION
  var source6 = ss.getRange ("E49");
  var destRange = destSheet.getRange(destSheet.getLastRow(),6);
  source6.copyTo (destRange, {contentsOnly: true});
}

I need this operation to be done only if the report number value does not exist in the column 2 of destination sheet.

How can it be done?

Best Answer

First your script should read the values of Column 2

Let say that you use destSheet.getRange(2,2,sheet.getLastRow(),1).getValues() then you could use a JavaScript loop to iterate over all the values or use a Array method like Array.some(callback) that returns true if any of the values meet the callback test.

As getValues() return a 2D array, the statement could look as following

var valueToLookForFound = values.some(function(row){
  return row[0] === valueToLookfor;
}

valueToLookForFound will be true if the valueToLookFor was found.

References