Google spreadsheets: Hide columns based on cell va

2019-02-14 02:47发布

问题:

In my google spreadsheet A, I use a combination of the TRANSPOSE and IMPORTRANGE formulas to import data from calendar spreadsheet B, in order to fill out a working schedule for events. Because on each date there are 3 event slots, which are not always filled, I am getting a lot of obsolete columns.

Table layout:

row1:  01-01-2013  01-01-2013  01-01-2013  02-01-2013
row2:  Event_ID    Event_ID    Event_ID    Event_ID
row3:  Event_name  Event_name  Event_name  Event_name

Rows 1 and 2 contain auto-generated dates and event_ID's so these are never empty. Cell nr. 3 displays empty when there was no event added to that slot, but in fact there is a CONTINUE-formula in there to continue the importrange-formula from cell A1.

I´m looking for a script to automatically hide the colums in which cell nr. 3 doesn't contain imported data.

Not understanding a thing about JavaScript (but willing to learn), I have tried to combine pieces from existing scripts but at this point I cannot manage to make any sense of these codes...

回答1:

The following code does the trick:

function onOpen() {
  // get active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // create menu
  var menu = [{name: "Hide columns", functionName: "hideColumn"},
    {name: "Show all columns", functionName: "showColumn"}];

  // add to menu
  ss.addMenu("Check", menu);
}

function hideColumn() {
  // get active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // get first sheet
  var sheet = ss.getSheets()[0];

  // get data
  var data = sheet.getDataRange();

  // get number of columns
  var lastCol = data.getLastColumn()+1;

  Logger.log(lastCol);

  // itterate through columns
  for(var i=1; i<lastCol; i++) {
     if(data.getCell(3, i).getValue() == '') {
        sheet.hideColumns(i);
     }
  }
}

function showColumn() {
  // get active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // get first sheet
  var sheet = ss.getSheets()[0];

  // get data
  var data = sheet.getDataRange();

  // get number of columns
  var lastCol = data.getLastColumn();

  // show all columns
  sheet.showColumns(1, lastCol);
}
  1. Creates menu upon opening file
  2. First menu option, hides all columns with row 3 being empty
  3. Second option, shows all hidden columns

See example file I prepared to watch it in action: Hide columns based on cell value



回答2:

In addition to Jacob's answer, it is possible to write a filter into the formula itself to only display columns with data in row 3. For example, if your ImportRange formula in A1 is:

=ImportRange("key";"A1:Z3")

you could instead use this:

=FILTER(ImportRange("key";"A1:Z3");LEN(ImportRange("key";"A3:Z3")))

or this, which uses only one ImportRange call:

=TRANSPOSE(QUERY(TRANSPOSE(ImportRange("key";"A1:Z3"));"select * where Col3 != ''"))