Home > Enterprise >  I want to show / hide rows with macros in google sheets
I want to show / hide rows with macros in google sheets

Time:05-31

/* What I want with this code using macros is to hide and show multiple columns BUT with the same button. However, it does not give the expected results. I need your help. */

function Show_Hide() {
  var spreadsheet = SpreadsheetApp.getActive();
  var status = 1;

  function Show() {
    spreadsheet.getActiveSheet().getColumnGroup(3, 1).expand();
    status = 1;
  };

  function Hide() {
    spreadsheet.getActiveSheet().getColumnGroup(3, 1).collapse();
    status = 0;
  };

  if (status==1){
    Hide();
  } else{
    Show();
  }
}

CodePudding user response:

The error in your code is that you are setting status to 1, and then checking if it is equal to 1. (It will always equal 1 with this logic).

Instead,

Try

function ShowHide() {

  const targetGroup = SpreadsheetApp.getActive()
                                    .getActiveSheet()
                                    .getColumnGroup(3, 1)

  return (targetGroup.isCollapsed())
  ? targetGroup.expand()
  : targetGroup.collapse()

}

This will check if the specified column group .isCollapsed(), if so it will be expanded, if not it will be collapsed.

Learn More:

  • Related