Skip to content

Instantly share code, notes, and snippets.

@bytrangle
Created May 25, 2020 09:42
Show Gist options
  • Save bytrangle/fedf836110e520624df7e21dbdb9b491 to your computer and use it in GitHub Desktop.
Save bytrangle/fedf836110e520624df7e21dbdb9b491 to your computer and use it in GitHub Desktop.
Auto generate sorta unique IDs for each row in Google Sheets
// This script fires when any cell is edited and the corresponding ID cell
// on the same row is empty. It will insert a reasonably unique UID of ID_length
// into the specified ID cell under the ID column.
// replace this with your sheet name
var ID_length = 5;
var targetSheet = 'Tasks';
// The header name of the column that stores unique IDs
var idHeader = 'Task ID';
// This function will get all the header names of the specified data range
// and their corresponding column number.
function getHeaderColumns(sheetName, startValue) {
var ss = SpreadsheetApp.getActiveSpreadSheet();
var sheet = ss.getSheetByName(sheetName);
// Return a range bounded by cell A1 and the last row and last column with content
// The range can be a single cell, or a rectangle of multiple rows and multiple
// columns, like B3:N75
var allData = ss.getDataRange().getValues();
var obj = {};
// Loop through each row of the range. The loop starts from 1 because row 1 in the
// spreadsheet are used as page margin
Loop1: for (var i = 1; i < allData.length; i++) {
var curRow = allData[i];
// Loop through each column. The inner loop also starts from 1 because column A
// are used as page margin
Loop2: for (var j = 1; j < curRow.length; j++) {
// The startValue variable refers to the value in the top left cell of the range.
// Because Google Sheets works like a sandbox, there may be data in the sheets
// that don't belong to a table. This double looping provides a failsafe mechanism
// account for that case.
if (curRow[j] === startValue) {
// Save the row number of the table header. It is 1 value larger than i because
// rows in Google Sheets start at 1, while standard Javascript arrays use zero-
//-based indexing.
obj['row'] = i + 1;
obj[['col'] = j + 1;
obj['cols'] = {};
curRow.forEach(function(elem, index) {
obj['cols'][elem] = index + 1;
})
break Loop1
}
}
}
// Example of obj: [{'row': 3, 'col': 2, cols: {'Status': 2, 'Task Name': 3, 'Task ID': 4}}
return obj;
}
function onEdit(e) {
var ss = e.source.getActiveSheet();
var sName = ss.getName();
if (sheet !== targetSheet) return;
var headerObj = getHeaderColumn(sName, 'Status');
var thisRow = e.range.getRow();
var idCol = headerObj[idHeader];
var idCell = ss.getRange(thisRow, idCol);
// ONly generate unique ID if the ID cell is blank
if (idCell.isBlank()) {
idCell.setValue(generateUID());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment