Skip to content

Instantly share code, notes, and snippets.

@caseypugh
Last active October 1, 2020 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caseypugh/361a864e867796c4bc786b38c6ff6b74 to your computer and use it in GitHub Desktop.
Save caseypugh/361a864e867796c4bc786b38c6ff6b74 to your computer and use it in GitHub Desktop.
Create unique IDs and timestamps for new Google Sheet entries
function onEdit(event)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var actSht = event.source.getActiveSheet();
var actRng = event.source.getActiveRange();
var curRowIndex = actRng.getRowIndex();
var date = Utilities.formatDate(new Date(), "GMT-4", "MM/dd/yyyy HH:mm:ss");
// Find column names
var columnNames = actSht.getRange("1:1").getValues();
for (var i = 0; i < columnNames[0].length; i++)
{
var cell = actSht.getRange(curRowIndex, i+1);
if (columnNames[0][i] == "Created At" && cell.getValue() == "" && curRowIndex != 1)
{
cell.setValue(date);
}
else if (columnNames[0][i] == "Updated At" && curRowIndex != 1)
{
cell.setValue(date);
}
else if (columnNames[0][i] == "id" && curRowIndex != 1)
{
if (cell.getValue() == "")
{
var headerCell = actSht.getRange(1, i+1);
var lastId = parseInt(headerCell.getNote());
ss.toast(lastId + 1);
headerCell.setNote(lastId + 1);
cell.setValue(lastId + 1);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment