Search code examples
google-sheetsgoogle-apps-script

Compare two cells and input timestamp in third if they do not match Google Apps Script


I have two lists that include IDs that I'd like to include a timestamp to a cell if the two columns don't match. I am able to do this easily with a function, but I need something that will act as a trigger for another action and a formula solution won't do that.

I have very little experience in Google Apps Scripts and I don't even know where to begin. I've tried searching here and all over the internet and haven't found anything yet.

Below is an example of the result I would like to see:

enter image description here

Thanks in advance for your help!


Solution

  • Compare Values and Add Timestamp If Not the Same

    You may use simple if-else (in this case ternary) to compare if the two values are the same and then return timestamp when the two values are not the same.

    Script

    You may use the following script:

    function compare() {
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data1 = ss.getRange(2, 5, ss.getLastRow() - 1, 1).getValues();
      var data2 = ss.getRange(2, 7, ss.getLastRow() - 1, 1).getValues();
      var out = data1.map((x, i) => (x == "" && data2[i] == "") ? [""] : parseInt(x) == parseInt(data2[i]) ? [""] : [Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy HH:mm:ss")]);
      ss.getRange(2,6,out.length,1).setValues(out);
    }
    

    Sample Data & Output

    enter image description here

    References: