Home > front end >  Hide/unhide certain columns with a custom menu
Hide/unhide certain columns with a custom menu

Time:12-16

I'm using a script based on another script I found here. It will hide certain columns based on the menu option selected but "View All" shows all columns across all spreadsheets. I need it to only show the columns that were hidden by using the script. I can't figure out the correct way to unhide specific columns.

Here's the code I'm using. I need columns 1, 2, 3 to remain hidden and never show up (on both worksheets) but I've added them to the code for now so that they will hide back until I can find a better solution.

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('CheckOff')
    .addItem('Hide', 'hideColumnsL')
    .addItem('View all', 'showColumns')
    .addToUi();
}

function showColumns() {
  const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  showColumnsInAllSheets_(sheets);
}

function hideColumnsL() {
  const obj = [{ sheetName: "Sheet1", hide: [1, 2, 3, 12, 13, 14] }, { sheetName: "Sheet2", hide: [1, 2, 3, 13, 14, 15] }];
  sample_(obj);
}


function sample_(obj) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = ss.getSheets();
  showColumnsInAllSheets_(sheets);
  const sheetObj = sheets.reduce((o, s) => (o[s.getSheetName()] = s, o), {});
  obj.forEach(({ sheetName, hide }) => {
    if (sheetObj[sheetName]) {
      hide.forEach(h => sheetObj[sheetName].hideColumns(h, 1));
    }
  });
}

function showColumnsInAllSheets_(sheets) {
  sheets.forEach(s => s.showColumns(1, s.getMaxColumns()));
}

CodePudding user response:

As a quick fix, try this in showColumnsInAllSheets_():

  sheets.forEach(s => s.showColumns(4, s.getLastColumn()));

CodePudding user response:

Show and hide columns:

function hideColumns() {
  const ss = SpreadsheetApp.getActive();
  const incl = [{ sheetName: "Sheet1", hide: [1, 2, 3, 12, 13, 14] }, { sheetName: "Sheet2", hide: [1, 2, 3, 13, 14, 15] }];
  incl.forEach((obj,i) => {
    let sh = ss.getSheetByName(obj.sheetName);
    obj.hide.forEach(c => sh.hideColumns(c))
  })
}

function showColumns() {
  const ss = SpreadsheetApp.getActive();
  const incl = [{ sheetName: "Sheet1", hide: [1, 2, 3, 12, 13, 14] }, { sheetName: "Sheet2", hide: [1, 2, 3, 13, 14, 15] }];
  incl.forEach((obj,i) => {
    let sh = ss.getSheetByName(obj.sheetName);
    obj.hide.forEach(c => sh.showColumns(c))
  })
}
  • Related