Home » excel » excel – Filter a table using an array

excel – Filter a table using an array

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to filter a table using an array.

The issue may be in how I’m setting the array up. The code runs, but does not filter the table.

Sub DataQuery()

    Dim wordDict As Object: Set wordDict = CreateObject("Scripting.Dictionary")
    Dim i, x As Integer
    Dim searchCol, searchText, demoText As String
    Dim searchVals() As String

    searchCol = "I"
    i = 3

    With Sheets("Query Sheet")
        searchText = Range(searchCol & i).Value
        searchVals() = Split(searchText, "|")
        For x = LBound(searchVals) To UBound(searchVals)

            Sheets("Total_Data").Range("A1").AutoFilter _
                Field:=2, _
                Criteria1:=searchVals(x), _
                Operator:=xlFilterValues
        Next x
    End With
End Sub

To give some context, I have a cell that has text such as: 11/5/2019|11/6/2019|11/7/2019.

I’m trying to break the text out by the pipe delimiter at the place where you see the Split(…) code, then use each of those values in a loop to add multiple filters to a single column on a table.

I’ve tried renaming my arrays, declaring them as variants, using scripting dictionaries.

How to&Answers:

So apparently, I’m just kinda dumb when it comes to arrays. I made one slight change to the code where you see the AutoFilter… piece.

Sub DataQuery()

    Dim i, x As Integer
    Dim searchCol, searchText, demoText As String
    Dim searchVals

    searchCol = "I"
    i = 3

    With Sheets("Query Sheet")
        searchText = .Range(searchCol & i).Value
        MsgBox searchText
        searchVals = Split(searchText, "|")
        Sheets("Total_Data").Range("A1").AutoFilter _
            Field:=2, _
            Criteria1:=searchVals, _
            Operator:=xlFilterValues
    End With
End Sub

Changing that to not filter by searchVals(x) and instead using the whole array at once fixed the issue.

Thanks for all your help!