按索引而不是按名称调用自动筛选条件

时间:2018-03-01 01:35:55

标签: excel vba

有没有办法通过索引而不是名称来应用自动筛选条件?目前,如果我想通过" apple"过滤列F,我的代码将是:

Worksheets("Data").Range("F:F").AutoFilter Field:=1, Criteria1:="apple"

但是,我只希望标准成为自动过滤器下拉列表中出现的第一个项目。像Criteria1:= 1这样的东西。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

这将返回将用于您的过滤条件的第一个项目。

<强>要求:

在我使用.Net SortedList类时需要安装.Net;通过.Net框架,通过System.Collections访问。

使用字典或集合代替排序列表:

很容易看到如何修改这个已排序的字典或集合。

如果您正在考虑对字典或集合进行排序(根据@ Jeeped的评论),您可以查看Chip Pearson的sorting functions

使用其他列获取第一个下拉项:

改变以下两个变量

1)targetColumn您感兴趣的专栏,例如&#34; A&#34;&#34; B&#34; ....

2)headerRow到标题所在的行,例如1,2 .....

您的例子:

现在,我添加了这一行:

 targetSheet.Range("F:F").AutoFilter Field:=1, Criteria1:=GetFilterCriteria(targetValues)

所以你可以在你给出的例子中看到它是如何工作的。但是,这确实需要您的数据从F列开始,因为您在第一个字段上进行过滤。

代码运行示例:

Filtering range

<强>代码:

Option Explicit

Public Sub testCall()

    Dim targetBook As Workbook
    Dim targetSheet As Worksheet

    Set targetBook = ThisWorkbook
    Set targetSheet = targetBook.Worksheets("Data")

    Const targetColumn As String = "F" 'this could be shifted to local variables
    Const headerRow As Long = 1

    Dim endRow As Long

    endRow = GetLastRow(targetSheet, targetColumn)

    If endRow < 2 Then

        MsgBox "No data to filter below header row in target column"
        Exit Sub

    End If

    Dim targetValues()

    targetValues = targetSheet.Range(targetColumn & headerRow + 1 & ":" & targetColumn & endRow).Value

    Dim filterCriteria As String

    filterCriteria = GetFilterCriteria(targetValues)

    MsgBox "Your filter criteria for column " & targetColumn & " is " & GetFilterCriteria(targetValues)

    targetSheet.Range("F:F").AutoFilter Field:=1, Criteria1:=GetFilterCriteria(targetValues)

End Sub
Public Function GetFilterCriteria(ByRef targetValues As Variant) As String 'this will become a function returning a string , accepting a range as parameter

    Dim orderedList As Object
    Set orderedList = CreateObject("System.Collections.SortedList") 'requires .Net framework installed. Otherwise order a dictionary or collection.See here: http://www.cpearson.com/excel/CollectionsAndDictionaries.htm

    Dim currentItem As Long

    On Error Resume Next                         'so ignore if item already in list

    For currentItem = LBound(targetValues, 1) To UBound(targetValues, 1)

        orderedList.Add targetValues(currentItem, 1), targetValues(currentItem, 1)

    Next currentItem

    On Error GoTo 0

    GetFilterCriteria = orderedList.GetByIndex(0)

End Function
Public Function GetLastRow(ByVal targetSheet As Worksheet, ByVal targetColumn As String) As Long

   GetLastRow = targetSheet.Cells(targetSheet.Rows.Count, targetColumn).End(xlUp).Row

End Function