按列表过滤表格

时间:2015-03-27 12:13:36

标签: excel excel-vba excel-formula vba

我有一个表,其中第一列是名称列表(在此示例中为食物列表),我需要通过使用列表过滤此列来对表进行排序。在这种情况下,我需要对" Food"表格由" Fruit"或"甜点",以便如果" Fruit"在Cell" E1"中选择,表格仅显示食物是" Apple"," Banana"或" Grapes" 。

我尝试使用Excel / Vba的INDIRECT功能进行依赖下拉列表,但这并不起作用。

甚至可以在Excel中执行此操作吗?如果需要使用VBA,我该怎么做?

enter image description here

2 个答案:

答案 0 :(得分:1)

如果你坚持使用VBA ......

Sub ert()

ListName = Range("F1") 'the filter cell, e.g. "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, e.g. "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试验,请参阅我的uploaded file

答案 1 :(得分:0)

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

 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