我想问用户:
我想将这些 n 过滤器作为输入并将它们应用到该列的字段。
参考这些图片: Before applying filters, After applying filters to Column 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
输入:1,2,A,B
我意识到我多次选择Criteria1
次。我发现了以下代码:
Range("A1:D10").AutoFilter Field:=1, Criteria1:=Array("A", "B"), Operator:=xlFilterValues
上面的代码完美无缺,但是我必须对值进行硬编码" A"和" B"。有没有办法用 n 用户输入替换它?
任何帮助将不胜感激!
修改 更进一步,如何将列数作为用户输入并将多个过滤器应用于多个列?
示例: (参考图片)
列:1,2(&#34;文档类型&#34;,&#34;年&#34;) 过滤器:第1列中的2(&#34; A&#34;,&#34; C&#34;),第2列中的2(&#34; 2016&#34;,&#34; 2017&#34;)< / p>
答案 0 :(得分:1)
尝试用简单的方法替换所有With
块:
'Apply multiple filters
Sheets("Sheet1").Cells.AutoFilter colNumber, Filters, xlFilterValues
此外,如@Jeeped所述,您需要根据用户输入调整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