Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-sheets-apigoogle-docs-api

"TypeError: Cannot read property 'length' of undefined" Converting Google Sheet data into a Google Doc template using Google Apps Script


Google sheet folder containing files: https://drive.google.com/drive/folders/1hPKQk7eRjSdlMDjiZI2BZrHIRhzVtYG5?usp=sharing

Im trying to fill out templates in google docs using data from my Test Merge google sheet file, specifically in the tab named "PrintThis". I have a Google Apps script added to my "Test Merge" google sheet file but im getting this error: "TypeError: Cannot read property 'length' of undefined". The data in PrintThis will be varying in the number of rows so I am guessing the error is caused by this line?

    var tactics = Sheets.Spreadsheets.Values.get('1xSWskGS8B_3Y35I4ycAjFZQiGbfJo13O3837RKnxnpk', 'A4:J');    

But when I do A4:J6 just to test it for this static set of data it still gives me the same error. How do I fix this in a way that even when the PrintThis tab has a dynamic number of rows and my PrintThis tab can be moved(ex. a new sheet/tab can be placed on the left or right of the PrintThis tab)?


Solution

  • If you want to get the value of "Test Merge" using Sheets API, make sure to add the sheet name along with the range. Example: "Test Merge!A4:J"

    Example:

    Test Data

    Code:

    function myFunction() {
    
      Logger.log(Sheets.Spreadsheets.Values.get('somespreadsheetid', 'Test Merge!A4:J').values);
    }
    

    Output:

    Test Data1

    Or

    Since you are using Google Apps Script, you could use SpreadsheetApp.

    Code:

    function myFunction() {
      var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test Merge");
      var range = sh.getRange(4, 1, sh.getLastRow() - 4 + 1, 10);
      var val = range.getValues();
      Logger.log(val)
    }
    

    Output:

    enter image description here

    References:

    SpreadsheetApp

    Method: spreadsheets.values.get