0

This code fails with:

TypeError: can't call method "getSheetName" of undefined. (line 7)

Code:

function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();
    var sheetnames = [];

    for(var i=0; i < sheets.length+1; i++)
        sheetnames.push(sheets[i].getSheetName());

    return ss.toast(sheetnames, "Greetings!", 300);
}

when this works:

function onOpen() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();
    var sheetnames = [];

    for(var i=0; i < sheets.length+1; i++)
        sheetnames.push(sheets[0].getSheetName());

    //Returns: Nimikirjasto,Nimikirjasto,Nimikirjasto,Nimikirjasto,Nimikirjasto
    // Text is too long to fit to the popup.
    return ss.toast(sheetnames, "Greetings!", 300);
}
1

Use the following code.

Code

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var shs = ss.getSheets(), num = shs.length;
  var sheetnames = [];

  for(var i=0; i<num; i++) {
    sheetnames.push(shs[i].getSheetName());
  }

  return ss.toast(sheetnames, "Greetings!", 300);
}

Explained

The sheets are zero based (as arrays are). So, adding an extra sheet in the iteration will result in an error (because of an unknown sheet index).

Remark

Your second code will always work, because the first entry (zero) will always be found. Try this, if you want to stack the sheet names:

sheetnames.push(shs[i].getSheetName() + '\n');

Reference

5
  • But the first code has i init as 0, which is same in the second, but it still fails. Unless, I'm overlooking and/or missing something. Jun 27 '14 at 15:13
  • @rautamiekka See sheets.length + 1 Jun 27 '14 at 15:33
  • Will take time before I fully get into the understanding of this. Outta interest, why did you add the brackets to the for I didn't have there ? Jun 27 '14 at 15:35
  • @rautamiekka Added some useful references, for those new to JavaScript. Jun 27 '14 at 16:41
  • Anyway, it's fixed, so thanks for that :) Jun 27 '14 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.