Search code examples
google-sheetsgoogle-apps-scriptnamed-ranges

Programmatically build a hyperlink to a named range in Sheets


I have a spreadsheet with lots of named ranges, and I'd like to have a sort of table of contents which provides hyperlinks to jump to them.

In the UI I can create a hyperlink to a named range, which ends up with the format:

https://docs.google.com/spreadsheets/d/xxxxx/edit#rangeid=yyyyy

Where xxxx is a long spreadsheet id, and yyyy is a series of digits.

Since I have an awful lot of these, I'd like to use Google Apps Script to generate all of these links programatically. I can find the named range objects using Spreadsheet.getRangeByName, but I can't find a way to get a rangeid from this.


Solution

  • It doesn't appear that this is possible, but as a workaround, Karl_S suggested using a range link which does work:

    function createNamedRangeUrl(name) {
      var root = SpreadsheetApp.getActiveSpreadsheet(); 
      var range = root.getRangeByName(name); 
      var sheetId = range.getSheet().getSheetId(); 
      var rangeCode = range.getA1Notation(); 
      return ("https://docs.google.com/spreadsheets/d/" + 
      root.getId() + "/edit#gid=" + sheetId + "&range=" + rangeCode); 
    }