简体   繁体   中英

Google apps script - automatically filter the active sheet

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM