Search code examples
javascriptgoogle-apps-scriptgoogle-sheets

How to iterate through all sheets using google script?


I want to iterate through all the tabs in a google spreadsheet and get their names. I tried using this function:

function init(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
 for (var i = 0; i < sheets.length; i++) {
    var r = sheets[i]
    Logger.log("sheet name:", r)
}
}

But the out-put that I get from this is:

sheet name: Sheet
sheet name: Sheet
sheet name: Sheet
sheet name: Sheet
sheet name: Sheet

Any suggestions about what I am doing wrong.


Solution

  • The script is logging the sheet object {}, which when stringified returns a literal Sheet string. You need to get it's name by calling the Sheet class' method getName():

    Logger.log("sheet name:", r.getName())