根据用户input应用多个filter(VBA)

我想问用户:

  1. 哪个字段/列应用filter?
  2. 要应用多less个filter?

我想把这n个filter作为input,并将它们应用到该列的字段。

参考这些图像: 在应用filter之前 , 将filter应用于A列

码:

Sub MultiFilter() Dim colNumber As Integer, numberOfFilters As Integer Dim filters(10) As String 'Column number to apply filters to colNumber = InputBox("Enter column number to apply filter to (Column A = 1, B = 2, etc.)") 'Number of filters to apply numberOfFilters = InputBox("Number of filters to apply to Column " & colNumber) 'Take multiple filters as input For i = 0 To numberOfFilters - 1 filters(i) = InputBox("Filter #" & i + 1) Next i 'Apply multiple filters With ThisWorkbook.Sheets("Sheet1") .Activate .Range("A1").Select .Range(Selection, Selection.End(xlToRight)).Select Selection.AutoFilter For i = 0 To numberOfFilters - 1 'ISSUE! Selection.AutoFilter field:=colNumber, Criteria1:=filters(i) Next i End With End Sub 

input:1,2,A,B

我意识到我正在多次selectCriteria1 。 我遇到了以下代码:

Range("A1:D10").AutoFilter Field:=1, Criteria1:=Array("A", "B"), Operator:=xlFilterValues

上面的代码完美的工作,但我必须硬编码值“A”和“B”。 有没有办法用n个用户input来replace?

任何帮助,将不胜感激!

编辑:更进一步,我如何作为用户input的列的数量和多个列应用多个filter?

示例:(参考图像)

列:1,2(“文档types”,“年份”)filter:列1中的2(“A”,“C”),列2中的2(“2016”,“2017”)

尝试用简单的方法replace所有的With团体:

  'Apply multiple filters Sheets("Sheet1").Cells.AutoFilter colNumber, Filters, xlFilterValues 

另外,正如@Jeeped所述,您需要根据用户input来调整filters数组大小

 Dim filters() As String ' <--- dont specify size here .... 'Number of filters to apply numberOfFilters = InputBox("Number of filters to apply to Column " & colNumber) Redim filters(0 to numberOfFilters - 1) As String '<-- resize according to user input