Accessing a Sheet by GID with Apps Script
The GID in a URL specifies which sheet to display upon opening.
For example, by specifying the GID in the URL of this document, it's the third sheet that is displayed upon opening:
https://docs.google.com/spreadsheets/d/1XspFDspoZwJGHuoc5zbnmhV_1ZxX6162Qmmzs7dXoOc/edit#gid=1587721123
Apps Script
Sometimes it's useful to access a sheet in an Apps Script based on its GID.
In this case, start by copying the getSheetByGID function provided here:
function getSheetByGID(spreadsheet, gid) {
// Source : https://sheets-pratique.com/en/codes/sheet-by-gid
return spreadsheet.getSheets().reduce((a, v) => !a && v.getSheetId() === Number(gid) ? v : a, 0);
}
And here's an example of how to use this function to retrieve the third sheet of the document mentioned at the beginning of the page:
function test() {
// Example document
const ss = SpreadsheetApp.openById('1XspFDspoZwJGHuoc5zbnmhV_1ZxX6162Qmmzs7dXoOc');
// Retrieving sheet 3 using the getSheetByGID function
const sheet3 = getSheetByGID(ss, 1587721123);
// Verification
console.log(sheet3.getName()); // Displays "Example 3"
}