4

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.

Marios
  • 26,333
  • 8
  • 32
  • 52
Max Di Campo
  • 408
  • 1
  • 4
  • 12
  • 1
    That's probably true. That's why I like to dabble with answers like this because you guys will catch me and I will learn something. – Cooper Feb 11 '21 at 13:03
  • 1
    @Cooper I am also here for the same thing. I asked you that to learn if this could work. Thank you too. – Marios Feb 11 '21 at 13:07

1 Answers1

4

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;
}
Marios
  • 26,333
  • 8
  • 32
  • 52