Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jalbertbowden/897853ee70e05f2566d2e05166ec60a6 to your computer and use it in GitHub Desktop.
Save jalbertbowden/897853ee70e05f2566d2e05166ec60a6 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

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