List Sheet Names and URLs for Each Sheet

From Renee Brooks
Jump to navigation Jump to search
  1. Create a Google Sheet that has a ton of sheets
  2. Create a new Sheet that is left-most of all of the other sheets in the Google Sheet and name it Index
    1. If you wish to use something other than Index, you can change the Sheet Name to whatever you like, but in this code below, you will want to replace Index with what your desired sheet name is
    2.   var sh=ss.getSheetByName('Index');
  3. Insert the code below to the Scripts section and hit save
  4. Go back to the Google Sheets and refresh the file. In the menu you should get a new option called, "Sheets" and within that menu, there will be "List All Sheets" and "List All URLs". Click on each in order until you have the list of links


function listSheets() {

  var sheetNames = new Array();

  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();

  var selectedSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var selectedRow = selectedSheet.getActiveCell().getRow();

  var selectedCol = selectedSheet.getActiveCell().getColumn();

  var range = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(selectedRow, selectedCol, sheets.length, 1);

  for (var i = 0; i < sheets.length; i++) sheetNames.push([sheets[i].getName()]);

  range.setValues(sheetNames);

}


function onOpen() {

  SpreadsheetApp.getUi()

      .createMenu('Sheets')

      .addItem('List All Sheets', 'listSheets')

      .addItem('List All URLS', 'listedSheetUrls')

      .addToUi();

}


function mySheetName() {

  var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();

  return key;

}


function listedSheetUrls() {

  var ss=SpreadsheetApp.getActive();

  var sh=ss.getSheetByName('Index');

  var rg=sh.getRange(1,1,sh.getLastRow(),1);

  var vA=rg.getValues();

  var nA=vA.map(function(r){return r[0];});

  var shts=ss.getSheets();

  shts.forEach(function(sh,i){

    var idx=nA.indexOf(sh.getName());

    if(idx!=-1) {

      var url=Utilities.formatString('https://docs.google.com/spreadsheets/d/%s/edit#gid=%s',ss.getId(),sh.getSheetId());

      vA[idx].splice(1,0,url);

    }

  });

  sh.getRange(1,1,vA.length,vA[0].length).setValues(vA);

}