A sheet URL ends in #gid=123456789. That number points at one tab and stays the same when someone renames it. getSheetByGid(ss, gid) finds the tab from that number, so a script keeps working after "Sheet1" becomes "Orders 2027".
When to use
- Scripts that take a pasted sheet link as input
- Config that should survive tab renames
- Matching a link in an email or doc to the right tab
How to use this snippet
/**
* Find a tab by its gid (the number after #gid= in the URL).
*
* @param {GoogleAppsScript.Spreadsheet.Spreadsheet} ss
* @param {number|string} gid
* @return {GoogleAppsScript.Spreadsheet.Sheet|null}
*/
function getSheetByGid(ss, gid) {
var target = Number(gid);
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetId() === target) return sheets[i];
}
return null;
}
Example
function openFromLink(url) {
var ss = SpreadsheetApp.openByUrl(url);
var gid = (url.match(/[#&]gid=(\d+)/) || [])[1] || 0;
var sheet = getSheetByGid(ss, gid);
if (!sheet) throw new Error('No tab with gid ' + gid);
return sheet;
}
Notes
- The first tab of a new spreadsheet is usually gid
0. - Copying a spreadsheet keeps the gids; duplicating a tab gives the copy a new one.
Happy Coding!
