Home > Enterprise >  How to get specific sheet by id in Google Apps script?
How to get specific sheet by id in Google Apps script?

Time:09-16

I want to define a specific sheet as an id value using the getSheetById() function.

It is said that getSheetId() is undefined and does not work.

The code I used is as follows.

function getSheetById(gid){
  for (var sheet in SpreadsheetApp.getActiveSpreadsheet().getSheets()) {
    if(sheet.getSheetId() == gid){
      return sheet;
    }
  }
}

CodePudding user response:

I believe your goal is as follows.

  • You want to retrieve the Sheet object by giving the sheet ID.

When I saw your script, in the case of for (var sheet in SpreadsheetApp.getActiveSpreadsheet().getSheets()) {}, sheet is index. I thought that this is the reason of your issue. In this case, how about using "for...of" as follows?

Modified script:

function getSheetById(gid){
  for (var sheet of SpreadsheetApp.getActiveSpreadsheet().getSheets()) {
    if(sheet.getSheetId() == gid){
      return sheet;
    }
  }
}

Or, I thought that in this case, find might be able to be also used as follows.

function getSheetById(gid) {
  return SpreadsheetApp.getActiveSpreadsheet().getSheets().find(s => s.getSheetId() == gid);
}
  • When the valid gid is given to the function getSheetById, the Sheet object is returned.
  • When the invalid gid is given to the function getSheetById, null is returned.

References:

  • Related