google-apps-scriptgoogle-sheetsgoogle-sheets-apigoogle-sheets-filter-view

Use Google App Script to insert new Filter View containing Custom Formula


Please see example picture below.

enter image description here

I would like to use Google Sheets script editor to add a Filter view on cell B3, that filters on a custom formula =(B4=$B$1).

The plan is to add a onEdit function that checks whether the value in cell B1 has changed, and if so reset the filter view in cell B3.

This is breaking my brain! I can't seem to find a way to auto update/refresh the filter once my value in B1 has changed.

My code currently looks like this, but this doesn't re-add the custom formula. It just keeps showing me all the non-empty rows.

function onEdit(e){
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sheetname = "Lactation";
  var sheet = ss.getSheetByName(sheetname);
  var erow = e.range.getRow();
  //Logger.log("DEBUG: row = "+erow);
  var ecolumn = e.range.getColumn();
  //Logger.log("DEBUG: column = "+ecolumn);
  if (erow == 1 & ecolumn == 2 ){
    // there is a match so the cell is B2
    //Logger.log("DEBUG: the cell is B2");
    updatefilter();
  }
  else
  {
    // there is no match so the cell is NOT I3
    //Logger.log("DEBUG: the cell is not I3");
  }

}

function updatefilter() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('B3').activate();
  var criteria = SpreadsheetApp.newFilterCriteria()
  .setHiddenValues(['', 'No'])
  .build();
  spreadsheet.getActiveSheet().getFilter().setColumnFilterCriteria(2, criteria);
};

Solution

  • If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

    Modification points:

    Modified script:

    In order to run the script, please edit the cell B1 on the sheet Lactation.

    function onEdit(e){
      var sheetName = "Lactation";
      var editCell = "B1";
    
      var range = e.range;
      var sheet = range.getSheet();
      if (range.getA1Notation() == editCell && sheet.getSheetName() == sheetName) {
        updatefilter(sheet);
      } else {
        // do something
      }
    }
    
    function updatefilter(sheet) {
      sheet.getRange('B3').activate();
      var criteria = SpreadsheetApp.newFilterCriteria().whenFormulaSatisfied("=(B4=$B$1)").build();
      var filter = sheet.getFilter();
      if (!filter) {
        filter = sheet.getRange("B3:B").createFilter();
      }
      filter.setColumnFilterCriteria(2, criteria);
    };
    

    Note:

    References:

    If I misunderstood your question and this was not the direction you want, I apologize.