google-apps-scriptgoogle-sheets

Get Google Sheet by ID?


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.


Solution

  • 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;
    }