1
votes

I have the below script which is intended to automatically filter the active sheet:

    function setFilter() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var filter = {};
      filter.range = {
        sheetId: tab.getActiveSheetId()
      };
    
      filter.criteria = {};
      // Which column to add the filter to
      var columnIndex = 0;
      filter['criteria'][columnIndex] = {
        'hiddenValues': ["✘"]
      };
      var request = {
        "setBasicFilter": {
          "filter": filter
        }
      };
      Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId());
    }

Unfortunately, I am getting a reference error mentioning that the tab isn't defined - what do I need to change? I have tried removing sheetID

1

1 Answers

0
votes

Explanation:

  • Use getActiveSheet to get the active sheet: var tab = ss.getActiveSheet()

  • Then use getSheetId to get the id of the active sheet: tab.getSheetId()

Solution:

 function setFilter() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var tab = ss.getActiveSheet(); // added code
      var filter = {};
      filter.range = {
        sheetId: tab.getSheetId() // modified code
      };
    
      filter.criteria = {};
      // Which column to add the filter to
      var columnIndex = 0;
      filter['criteria'][columnIndex] = {
        'hiddenValues': ["✘"]
      };
      var request = {
        "setBasicFilter": {
          "filter": filter
        }
      };
      Sheets.Spreadsheets.batchUpdate({'requests': [request]}, ss.getId());
 }

I assume you are already aware of that, but in order for the code to work you need to enable Google Sheets API from the Resources tab in the old editor or Services in the new editor.