按列表过滤表

我有一个表第一列是一个名称列表(在这个例子中,食物列表),我需要通过列表过滤这个列sorting表。 在这种情况下,我需要通过“水果”或“甜品”对“食物”表进行sorting,如果在“E1”单元格中select了“水果”,表格将只显示食物是“苹果” “,”香蕉“或”葡萄“。

我已经尝试使用Excel / VBA的INDIRECT函数做依赖下拉列表,但是这不起作用。

这甚至有可能在Excel中做? 如果这需要用VBA来完成,那我该怎么做?

在这里输入图像说明

如果你坚持使用VBA …

 Sub ert() ListName = Range("F1") 'the filter cell, eg "Dessert" ListNumerosity = Range(ListName).Cells.Count 'counts the numerosity of your list Dim MyList() As String 'creates list ReDim MyList(1 To ListNumerosity) 'sets numerosity of list Dim rng As Range For Each rng In Range(ListName) 'for each cell in your filter, eg "Dessert" i = i + 1 MyList(i) = rng 'collect the cell values into a list Next ActiveSheet.ListObjects("Táblázat3").Range.AutoFilter Field:=1, Criteria1:=MyList(), Operator:=xlFilterValues 'replace Táblázat3 with your tablename, does filtering to your list End Sub 

进一步的规格和f'd审判看到我上传的文件 。

这是我最终使用的整个模块。

  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