这是我最终使用的整个模块。
Sub FilterByArray()
Dim ary As Variant, Idx As Long, Jdx As Long
Dim numCols As Long, numRows As Long
Dim food As String, year As String
food = "Food"
year = "2015"
numNamedRanges = 0
SetDataValidation food, year
Sheets(food).Activate
numCols = Sheets(food).Range("A2", Range("Z2").End(xlToLeft)).SpecialCells(xlCellTypeVisible).Cells.Count
For Idx = 1 To numCols
numRows = Sheets(food).Range(Cells(2, Idx).Address, Range(Cells(499, Idx).Address).End(xlUp)).SpecialCells(xlCellTypeVisible).Cells.Count
' Add named ranges for 1 to numRows for each column in 1 to numCols
ActiveWorkbook.Names.Add Name:=Cells(1, Idx).Value, RefersTo:="=" & Cells(2, Idx).Address & ":" & Cells(numRows + 1, Idx).Address
Next Idx
For Idx = 1 To numCols
If Sheets(year).Cells(1, 6).Value = Sheets(food).Cells(1, Idx).Value Then
numRows = Sheets(food).Range(Cells(2, Idx).Address, Range(Cells(499, Idx).Address).End(xlUp)).SpecialCells(xlCellTypeVisible).Cells.Count
ReDim ary(1 To numRows)
For Jdx = 1 To numRows
ary(Jdx) = Cells(Jdx + 1, Idx).Value
Next Jdx
Sheets(year).ListObjects(1).Range.AutoFilter Field:=1, Criteria1:= _
ary, Operator:=xlFilterValues
Exit For
End If
Next Idx
Sheets(year).Activate
End Sub
Sub SetDataValidation(food As String, year As String)
Dim listArray As Variant, Idx As Long
Dim numCols As Long
Sheets(food).Activate
numCols = Sheets(food).Range("A2", Range("Z2").End(xlToLeft)).SpecialCells(xlCellTypeVisible).Cells.Count
ReDim listArray(1 To numCols)
For Idx = 1 To numCols
listArray(Idx) = Cells(1, Idx).Value
Next Idx
Sheets(year).Range("F1").Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Operator:=xlBetween, Formula1:=Join(listArray, ",")
End Sub