Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific sheet by its GID in Google Apps Script

With this:

getSheetByName('test');

I can select a Sheet by it's name. But how can I select it by the GID which is at the end of the url? In my example: "...edit#gid=1063355045"

I already tried something like getSheetById('1063355045'); - but this is not working.

like image 606
Max Di Campo Avatar asked Oct 23 '25 03:10

Max Di Campo


1 Answers

Explanation:

As you have also noticed, there is no such a method to get a sheet object by its id.

However, you can do some JavaScript tricks:

  • Get all the sheets of your document with getSheets().

  • Use getSheetId() to get the gid of all the sheets.

  • Filter on the one with the chosen gid.

Solution:

function myFunction(){
  const ss = SpreadsheetApp.getActive();
  const sheets = ss.getSheets();
  const gid = "1063355045"; // select the gid of your choice
  const sheet = sheets.filter(sh=>sh.getSheetId()==gid)[0]; // this is the sheet object
  console.log(sheet.getSheetName());
}

sheet is the desired sheet with the particular gid. You can apply all the sheet methods to that object.

Construct your own getSheetByGid function:

function myFunction(){
  const gid = "1063355045";
  const sheet = getSheetByGid(gid);
}

function getSheetByGid(gid){
  const ss = SpreadsheetApp.getActive();
  const sheets = ss.getSheets();
  const sheet = sheets.filter(sh=>sh.getSheetId()==gid)[0]; // this is the sheet object
  return sheet;
}
like image 161
soMarios Avatar answered Oct 25 '25 16:10

soMarios