google-sheetsgoogle-apps-script

Google Apps Script fails to retrieve sheet by name


I'm having a very strange and persistent issue with Google Apps Script and getSheetByName().

I have a Google Apps Script script connected to a Google Sheets spreadsheet. The script is supposed to read data from a specific sheet (which I've named various things during my attempts: Tasks, PROJECTS, TEMP_PROJECTS, and finally DATA) and create events in my Google Calendar.

The problem is that even though I specify the sheet name correctly with SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SHEET_NAME"), the execution log still says that it's finding a sheet called Sheet (which I assume is the default name of the first tab). As a result, the script can't find the correct data and doesn't create the events in the calendar.

What I've already tried (detailed list):

Questions:

Are there any settings at the spreadsheet or account level that could affect how getSheetByName() works? Could there be a very persistent "caching" or syncing issue? If so, how could I fix it?


Solution

  • The problem is that even though I specify the sheet name correctly with SpreadsheetApp.getActiveSpreadsheet().getSheetByName("SHEET_NAME"), the execution log still says that it's finding a sheet called Sheet (which I assume is the default name of the first tab)

    The default name of the first tab in a new spreadsheet is Sheet1 in the United States locale.

    Chances are that your code looks like this:

      var sheet = ss.getSheetByName('x');
      Logger.log(sheet);
    

    That means that you're not logging the sheet's name but a Sheet object. A sheet object is a JavaScript class that provides methods for accessing and manipulating the object's properties. When you blindly coerce it to a text string as in the above example, it will always render as Sheet. To log the sheet's name, use sheet.getName(), like this:

      const sheetName = 'x';
      const ss = SpreadsheetApp.getActive();
      const sheet = ss.getSheetByName(sheetName);
      if (sheet) {
        console.log(sheet.getName());
      } else {
        console.log(`Cannot find sheet ${sheetName}`);
      }
    

    When no sheet by the name given is found in the spreadsheet, sheet.getName() returns null.

    See Sheet.getName().