Search code examples
google-apps-scriptnamed-ranges

Google Sheets Script: Get Sheet a Named Range is On


Is there a way to get the Sheet that a Named Range is on? I list all my NRs on a separate sheet for reference, thanks to a script provided by @cooper, but I haven't found a method to also get the name (or index) for the sheet.

function c_NamedRangeToSpreadsheet() {
// Author: Cooper
// Link: https://stackoverflow.com/a/64841828/190925
// Purpose: Record all NamedRanges by both Name and Range
  const ss=SpreadsheetApp.getActive();
  const nrA=ss.getNamedRanges();
  const targetSh = "NamedRanges";  

  let sh=ss.getSheetByName(targetSh); 
  sh.clear(); // MH

  let rowA=[];
  for(let i=0;i<nrA.length;i++) {
    let name=nrA[i].getName();
    let range=nrA[i].getRange().getA1Notation();
    rowA.push([name,'','',range]);
  }
  rowA.sort(); // MH   
  sh.getRange(1,1,rowA.length,4).setValues(rowA);
}

Solution

  • You can get the sheet for a given range with the method getSheet(): https://developers.google.com/apps-script/reference/spreadsheet/range#getsheet

    After that, you can use getName() to get the sheet's name (https://developers.google.com/apps-script/reference/spreadsheet/sheet#getname) or getIndex() to get its index (https://developers.google.com/apps-script/reference/spreadsheet/sheet#getindex).