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

  • I implemented the feature request in https://issuetracker.google.com/36759083. You can now do the following with the getSheetById() method:

    function myFunction() {
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetById(0)
    
      console.log(sheet.getName());
    }
    

    The first sheet created has id 0. The id is not based upon position. For example, the second sheet created might have an id of 1982384720 and the third sheet, 1741408075.

    Note that there currently is a bug in sheet.getSheetId(), https://issuetracker.google.com/380057139.