Home > Software design >  Google Sheets call sheet by name based on cell value of current tab
Google Sheets call sheet by name based on cell value of current tab

Time:11-04

I am trying to hide or unhide specific tabs by creating functions. The problem is the sheet name will change depending on who's using it. Is it possible to get a sheet name based on the value of a cell on the current tab?

Example:

function HideIncOne() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('G18').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('INCENTIVE #1'), true);
  spreadsheet.getActiveSheet().hideSheet();
};

I tried .getSheetByRange but obviously that didn't work. So I'm trying to call the text from cell B4 of the current tab and make google sheets hide a sheet with the same name as the text in cell B4.

CodePudding user response:

  • Get the active sheet's B4 value
  • Get Sheet with that name using getSheetByName and hide it
function HideSheetInB4() {
  const spreadsheet = SpreadsheetApp.getActive();
  spreadsheet
    .getSheetByName(
      spreadsheet
        .getActiveSheet()
        .getRange('B4')
        .getValue()
    )
    .hideSheet();
}

CodePudding user response:

Here's a simple way to put developer metadata into selected sheets

In this case I only wanted to mess with my sheets that are named with the string "Sheet" followed by 1 or more digits.

Hence the regex /Sheet\d{1,}/ or /Sheet\d /

function addingmetadatatosomesheet() {
  const ss = SpreadsheetApp.getActive();
  ss.getSheets().forEach((sh, i) => {
    if (sh.getName().match(/^Sheet\d{1,}/)) {
      sh.addDeveloperMetadata('shidx', i   1);
    }
  });
}

This is how I read the meta data.

function findSheetMetaData() {
  const ss = SpreadsheetApp.getActive();
  ss.getSheets().forEach(sh => {
    let v = sh.createDeveloperMetadataFinder().withKey('shidx').find();
    if (v && v.length > 0) {
      v.forEach(e => {
        Logger.log(`SheetName: ${sh.getName()} Metadata: ${e.getValue()}`);
      });
    }
  });
}

Execution Log Output:

1:37:31 PM  Info    SheetName: Sheet01 Metadata: 7.0
1:37:31 PM  Info    SheetName: Sheet1 Metadata: 8.0
1:37:31 PM  Info    SheetName: Sheet2 Metadata: 9.0
1:37:32 PM  Info    SheetName: Sheet3 Metadata: 10.0
1:37:32 PM  Info    SheetName: Sheet4 Metadata: 11.0
1:37:32 PM  Info    SheetName: Sheet5 Metadata: 12.0
  • And this represent a solution that your casual user is not going to find easy to mess with.
  • Related