简体   繁体   中英

How to apply filters of spreadsheet using google apps scripts?

I need to apply a filter on a spreadsheet and then apply the filter on the active spreadsheet.

Tried using the Filter Class but not sure what is incorrect

'''
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("main sheet");
var dataMatrix1 = activeSheet.getRange(1, 1, activeSheet.getLastRow(), activeSheet.getLastColumn());

function applyFilter(){
  Logger.log("mark1");

  var filteredData = dataMatrix1.createFilter(); //filter created
  var a = 'a';
  filteredData.sort(1, false);
  filteredData.setColumnFilterCriteria(1 , a);

  Logger.log("Mark2");
}
'''

The spreadsheet has 2 rows with value = 'a' in the first column. Need to apply a filter to the sheet and filter out rows with value = 'a'.

You are very close to accomplish your request; you only need to create a filter criteria instead of using the a variable. You can see exactly which methods to use on the following code. Also, the filtered string must be inside of an array, so I sightly modified your a variable.

function applyFilter() {
  var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
    "main sheet");
  var dataMatrix1 = activeSheet.getRange(1, 1, activeSheet.getLastRow(),
    activeSheet.getLastColumn());

  var filteredData = dataMatrix1.createFilter(); //filter created
  var a = ['a'];
  filteredData.sort(1, false);
  var filterCriteria = SpreadsheetApp.newFilterCriteria().setHiddenValues(a)
    .build();
  filteredData.setColumnFilterCriteria(1, filterCriteria);
}

Please, do not hesitate to ask for more help if you keep having problems.

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