Skip to content
Advertisement

Automating named Range function in google sheets

Context

So I have a spreadsheet with 11+ sheets, though will be adding more later. I want to dynamically name the columns using named range. I created a macro script and have been using this. Only the problem is for every sheet, I have to go to the script and change the name of the named range:

function NamedRanges() {
      var spreadsheet = SpreadsheetApp.getActive();
      spreadsheet.setNamedRange('TrainlineDate', spreadsheet.getRange('A:A'));
      spreadsheet.setNamedRange('TrainlinePrice', spreadsheet.getRange('B:B'));
      spreadsheet.setNamedRange('TrainlineReturns', spreadsheet.getRange('C:C'));
      spreadsheet.setNamedRange('TrainlineGrossReturns', spreadsheet.getRange('D:D'));
      spreadsheet.setNamedRange('TrainlineGeometricReturns', spreadsheet.getRange('E:E'));
      spreadsheet.setNamedRange('TrainlineRisk', spreadsheet.getRange('F:F'));
      spreadsheet.setNamedRange('TrainlineNegativeReturns', spreadsheet.getRange('G:G'));
      spreadsheet.setNamedRange('TrainlinePositiveReturns', spreadsheet.getRange('H:H'));
      spreadsheet.setNamedRange('TrainlineTimeValueMoney', spreadsheet.getRange('I:I'));
    };

For example, for the next tab, I have to change Trainline to Softcat.

I tried my hand at creating the columns as an array and then a for loop to create a named range according to the name in cell B2 + the name in the headers (the 3rd row of every column). I will also be adding new columns in the future. But when I tried to log the value in cell B2 it failed. Long story short, I am stuck. This is what I came up with thus far;

function NamedRange() {
      const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var col = ss.getLastColumn(); //Get all the columns in the sheet with data (there will be no gaps/spaces)
      var stockName = ss.getRange("B1"); // name in cell B1 (column 2, row 1)
      var headerCell = ss.getRange(3, col); // in row 3 of all columns
      var rangeName = ss.getValue(stockName);         
      Logger.log(rangeName) // test to see if the value of stockname is picked up by Appscript

// For every column, get the values in 'stockName and headerCell' and create a named range from them. 
An exception is for the second column, instead of 'Close' name, call it 'Stockname' + 'Price'.
    };

Here is an example of the spreadsheet format. This script though will be applicable to Aveva Group tab onwards. Data for stock(s)

Problem

Typically the format of the spreadsheets will all be the same. The only difference will be the name of the stock. I want to be able to automatically set the namedRange of all columns for existing and new columns for every tab/sheet and trigger it using a custom menu (this part I can sort out myself). Is there a better way to get this done?

Advertisement

Answer

Explanation:

  • Create an array of all the sheet names you would like to be part of this process.

  • ForEach sheet name, set the name ranges according to that name by concatenating the sheet name with the namerange name.

Solution:

function NamedRanges() {
      var spreadsheet = SpreadsheetApp.getActive();
      //put all the sheets here you want to include
      var sheetNames = ["Trainline","Softcat","Avast"];
      var namerng=['Date','Price','Returns','GrossReturns','GeometricReturns',
                  'Risk','NegativeReturns','PositiveReturns','TimeValueMoney'];
      sheetNames.forEach(sh=>{
          sheet = spreadsheet.getSheetByName(sh);
          namerng.forEach((nr,i)=>{
           spreadsheet.setNamedRange(sh+nr, sheet.getRange(1,i+1,sheet.getMaxRows(),1));
          });
      });
};

Save also this code to your script editor and it will create a menu button at the top menu of the spreadsheet file that will execute NamedRanges:

function onOpen() {
  SpreadsheetApp.getUi()
  .createMenu('Custom Menu')
  .addItem('Name Ranges', 'NamedRanges')
  .addToUi();
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement