Create A Unique ID Using A Custom Function In Google Sheets

nightwolfdev - Apr 24 '23 - - Dev Community

Have you ever needed to uniquely identify a row in Google Sheets? You could use the row number, but if users move or delete rows, the numbers would change. What you need is a unique id for each row. Learn how to create a custom function that returns a unique id in Google Sheets!

Create A Custom Function

Create A Custom Function

  1. Open your spreadsheet and navigate to Extensions > Apps Script.
  2. The Apps Script Editor will open with a single script file called Code.gs.
  3. An empty function will default in. You can remove it.
  4. Give your untitled project a name.

In the Apps Script code editor, create a function called UUID.



function UUID() {

}


Enter fullscreen mode Exit fullscreen mode

Apps Script provides a Utilities class with a getUuid method. All we have to do is return it in the function.



return Utilities.getUuid();


Enter fullscreen mode Exit fullscreen mode

Here’s the final code for the UUID function.



function UUID() {
  return Utilities.getUuid();
}


Enter fullscreen mode Exit fullscreen mode

Use A Custom Function

Use A Custom Function

Using a custom function is no different than using the many functions Google Sheets provides. Within the cell, enter the function:



=UUID()


Enter fullscreen mode Exit fullscreen mode

The result will be a unique id!



baceef3c-f633-4deb-94db-1c17a2105719


Enter fullscreen mode Exit fullscreen mode

You can also use functions (and custom functions) when inserting rows. For example, when using the appendRow method of the Sheet class.



const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users');

sheet.appendRow([
  '=UUID()',
  'John',
  'Smith'
]);


Enter fullscreen mode Exit fullscreen mode

You can now uniquely identify rows using the id! This can be useful when making an edit to a specific row!


Visit our website at https://nightwolf.dev and follow us on Twitter!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .