Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter table in excel VBA based on a column of values

I have a table and I would like to filter the rows by the values in one of its columns. The values used to filter are stored in a separate column not in the table. This is what I have so far:

Dim table1 As ListObject
Dim range1 As Range
Set range1 = ActiveSheet.range("AM23:AM184")
'get table object
table1.range.AutoFilter Field:=3, Criteria1:=???

I do not know what to put for criteria1. I know it needs to be an Array and I can set it to something like Array("12","2","13") but what I need it to equal is the values specified in the range given by range1. Any help would be greatly appreciated.

EDIT: I have been able to get my range values into an Array by doing range1.Value and then converting the Variant into a string array. This did not work as I wanted it to as it just sets my Filter to the last value in my array. For instance, if my array contains the IDs ("12","44","13","22") and I set Criteria1 to that array and run it, the filter only has 22 selected and all other numbers are deselected including 12, 44, and 13.

like image 306
user972276 Avatar asked Apr 12 '13 17:04

user972276


1 Answers

I figured it out! I had tried recoding but the first time I tried it, it gave me an incomplete program due to too many lines associated with one line of code. So I redid the recording to give me the whole code and turns out I was missing something. Here is the whole code:

Dim range1 As range
Set range1 = ActiveSheet.range("AM23:AM184")
Dim var1 As Variant
Dim sArray() As String
Dim i As Long
var1 = range1.Value

ReDim sArray(1 To UBound(var1))

For i = 1 To (UBound(var1))
    sArray(i) = var1(i, 1)
Next

ActiveSheet.ListObjects("Table1").range.AutoFilter Field:=3, Criteria1:=sArray, Operator:=xlFilterValues

the "Operator:=xlFilterValues" was the key part I missed from recording the macro the first time because the recording stopped pre-maturely

like image 151
user972276 Avatar answered Sep 25 '22 01:09

user972276