Get Google Sheet by ID?

mrfinnsmith picture mrfinnsmith · Oct 31, 2014 · Viewed 57.9k times · Source

I know that Google Apps Script has a getSheetId() method for the Sheet Class, but is there any way to select a sheet within a spreadsheet by referencing the ID?

I don't see anything like getSheetById() in the Spreadsheet Class documentation.

Answer

Serge insas picture Serge insas · Oct 31, 2014

You can use something like this :

function getSheetById(id) {
  return SpreadsheetApp.getActive().getSheets().filter(
    function(s) {return s.getSheetId() === id;}
  )[0];
}

var sheet = getSheetById(123456789);

And then to find the sheet ID to use for the active sheet, run this and check the Logs or use the debugger.

function getActiveSheetId(){
  var id  = SpreadsheetApp.getActiveSheet().getSheetId();
  Logger.log(id.toString());
  return id;
}