Skip to content

Instantly share code, notes, and snippets.

@dannguyen
Last active April 30, 2021 17:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dannguyen/40c09a051a413e3a379ce240b3051c0b to your computer and use it in GitHub Desktop.
Save dannguyen/40c09a051a413e3a379ce240b3051c0b to your computer and use it in GitHub Desktop.
a Google Sheets script that automatically adds a timestamp to a corresponding row when the first column is created

How to automatically timestamp a column when a row in Google Sheets is created

Couldn't be bothered to look up the latest workout tracking app, so decided to stick to Google Sheets for now. One problem with this approach is that while it is easy on desktop GSheets to fill out a current timestamp (Command-Option-Shift-semicolon in MacOS), no such shortcut is available AFAIK in the iOS version of Google Sheets.

image

So I wrote a little custom function in Google Apps Script to do the following:

In an active Google Sheets spreadsheet, given a tab/sheet named myworkouts with a header named datetime, the following script updates a row's corresponding "datetime" column when a value is entered into a first column cell:

var SHEET_NAME = 'myworkouts';
var DATETIME_HEADER = 'datetime';

function getColByHeader(headerval){
  var headers = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getDataRange().getValues().shift();
  var colindex = headers.indexOf(headerval);
  return colindex+1;
}

function onEdit(e) {  
  var ss = SpreadsheetApp.getActiveSheet();
  var cell = ss.getActiveCell();
  var datecell = ss.getRange(cell.getRowIndex(), getColByHeader(DATETIME_HEADER));
  // Conditions: 
  //  - edited (active) cell is in the first column
  //  - edited cell is not blank
  //  - corresponding datetime cell is blank 
  //  - active sheet is named [SHEET_NAME]
  if (cell.getColumn() == 1 && !cell.isBlank() && datecell.isBlank() && ss.getName() == SHEET_NAME) {      
    datecell.setValue(new Date()).setNumberFormat("yyyy-MM-dd hh:mm");
  }
};

Note: technically this script doesn't update the datetime column upon cell creation (I don't think there is a onCreate() Simple Trigger). Instead, it looks to see if the corresponding datetime cell is empty when the onEdit() event for a first column cell is triggered.

More info

@bmcadams111
Copy link

hi there! attached is a screenshot of my code. it was working fine in a test worksheet, but when i tried to apply it to the actual spreadsheet i'm getting this error that i don't understand. can someone help? thanks!
Screen Shot 2021-04-30 at 10 05 09 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment