0
votes

I have about 50 sheets in my Google spreadsheet, and want to return different values from different sheets. However, I don't feel safe using the sheet names as a key by using getSheetByName as they are easy to change. I was wondering if there is any way to use the gid-ID I see changing for each spreadsheet as key? Or something else?

Below is what I am using now:

var ssValve = SpreadsheetApp.openById('Key').getSheetByName("SheetName")
3

3 Answers

2
votes

There's no native method, but you can build a function for this:

function getSheetById(masterSheet, sheetId) {
  var ss = SpreadsheetApp.openById(masterSheet);
  var sheet = ss.getSheets();

  for( i in sheet )
    if( sheetId == sheet[i].getSheetId())
      return sheet[i];

  return -1;
}
0
votes

YES! The gid is the unchangeable unique identifier for the individual sheets within the workbook.

It is surprising that you cant script with it as the basic identifier, Like GetSheetByID(). I'll be using your code in my sheets.

A suggestion to rename the mastersheet variable to something more standard like "spreadsheetKey" or "workbookKey".

-1
votes

You can use getSheetId().

var ssValve = SpreadsheetApp.openById('Key').getSheets()[0]

Change [0] to [1] [2] [3] and so on..for going from sheet1 to 2, 3 ,4 and so on

More info here