add current ts when editing a row in Google Sheets

js
google_docs
Author

David Dobrinskiy

Published

June 16, 2022

Intro

Go to Extensions -> Apps Script

Save this snippet as code. Because the function is named onEdit, sheets knows to run it every time the sheet is edited.

// Code.gs file
// don't forget to save & run (to get permissions)

function onEdit() {
  var colNum = 1  // hard coded number of column to put the date in
  var s = SpreadsheetApp.getActiveSheet();
  if( s.getName() === "Sheet 1" || s.getName() === "Sheet 2" ) { //checks that we're on the correct sheet
    var r = s.getActiveCell(); // r is our active cell
    if( r.getColumn() !== colNum ) { //checks the edited column
      var nextCell = s.getRange(r.getRow(),colNum); // next cell will be on the same row in column #colNum
      if( nextCell.getValue() === '' ) // is nextCell empty? DO NOT OVERWRITE EXISTING TIMESTAMPS
        nextCell.setValue(new Date());  // add current timestamp & date to second column
    }
  }
}

See this script in action:

https://github.com/ddobrinskiy/blog/blob/master/posts/2022/06/add_ts_to_gsheets/2022-06-16-add-current-ts-when-editing-Google-Sheets.ipynb
https://github.dev/ddobrinskiy/blog/blob/main/posts/2022/06/add_ts_to_gsheets/2022-06-16-add-current-ts-when-editing-Google-Sheets.ipynb