Google Sheets – How to Hide/Show a Group of Columns Easily

google sheets

I need to hide and show in a easy way a group of columns in Google Sheets.
In Excel I used a Macro with a button, but in Sheets I cannot put a button.

How can I add buttons with custom functions in Google Sheets?

Best Answer

It is possible to assign a function to a button in Google Spreadsheets, but in practice it's easier to add commands to the spreadsheet menu. This way you do not have to look for them in the spreadsheet, and they do not get in the way of your data.

Suppose you want custom commands "show/hide columns B-D, G". Create and save the following script in (Tools->Script Editor):

function onOpen() {
  var menu = [{name: "Show B-D, G", functionName: "showColumns"}, {name: "Hide B-D, G", functionName: "hideColumns"}]
  SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", menu);
}

function showColumns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.showColumns(2,3);   // B-D, three columns starting from 2nd 
  sheet.showColumns(7);      //  G, column number 7
}

function hideColumns() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  sheet.hideColumns(2,3);  // B-D, three columns starting from 2nd
  sheet.hideColumns(7);     // G, column 7
}

Next time you open this spreadsheet, it will have "Custom" menu option with two commands, for showing and hiding this range of columns.


If you still want to trigger scripts by an embedded element in the sheet, see this illustrated example.