Search code examples
arraysgoogle-apps-scriptgoogle-sheetsgoogle-sheets-macros

Apps Script (Google Sheets) How to perform .setHiddenValues with an Array


I have some values stored in an Array and now I want to remove ALL the values stored in this array from a filter. The values are stored correctly in the array but I don't manage to remove the values from the filter.

The Array's name is HideValues

Here is some code:

  var p = 0;

  spreadsheet.getSheetByName('TEM Tool Data').getRange('\'TEM Tool Data\'!E1').activate();
  var criteria = SpreadsheetApp.newFilterCriteria();

  //Remove all PID´s from the filter
  while (p < HideValues.length){
  criteria.setHiddenValues([HideValues[p]]).build();
  p++;}   

  //Filter
  spreadsheet.getSheetByName('TEM Tool Data').getFilter().setColumnFilterCriteria(5, criteria);

  //Copy filtered area
  spreadsheet.getRange('A2:I1386').activate();

  //Paste
  spreadsheet.getSheetByName('Visualization').getRange('A5').activate();
  spreadsheet.getRange('\'TEM Tool Data\'!A2:I1386').copyTo(SpreadsheetApp.getActiveRange(), 
  SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.getSheetByName('Visualization').getRange('J3').activate();
};

Solution

  • You don't need to loop through the array

    If your array is something like var HideValues = [1,2,3,4,5];,

    you can simply specify criteria.setHiddenValues(HideValues).build(); - without the while loop

    Also:

    1. To a filter, you should create it first (if not already done) and apply it to a range, not sheet:
      var filter = spreadsheet.getSheetByName('TEM Tool Data').getDataRange().createFilter();
      filter.setColumnFilterCriteria(3, criteria);
    
    1. You should apply it to a range, not a sheet