Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofilter Field using the header Name

Tags:

excel

vba

i tried to use the Autofilter function but using field with the header name "ID" instead the number of column. i tried my best and i got this error message "Advanced filter fails at iterations, run-time error 1004"

I am stuck for two days with it . thnk's for your help

code :

Sub AdataPreparation()
Dim WorkBk As Workbook, WorkSh As Worksheet, WrkTab As range, FilterRow As Variant
Set WorkBk = Workbooks.Open(Filename:="C:\Users\Documents\DataApplied.xlsm")
Set WorkSh = Sheets("sheet2") 
WorkSh.Activate 
Set WrkTab = range("A1").CurrentRegion 
WrkTab = ActiveRange
FilterRow = Application.Match("ID", WrkTab, 0)
Selection.AutoFilter Field:=FilterRow, Criteria1:="="
End Sub
like image 781
DataScientist Avatar asked Oct 20 '25 06:10

DataScientist


1 Answers

The issue probably lies in not having anything selected for your .Autofilter to filter. Try replacing Selection with a range, or the .UsedRange.

You also don't need WrkTab, I don't see it having any purpose - here I use .Find instead:

Sub AdataPreparation()
Dim WorkBk As Workbook, WorkSh As Worksheet, FilterRow As Variant

Set WorkBk = Workbooks.Open(Filename:="C:\Users\Documents\DataApplied.xlsm")
Set WorkSh = Sheets("sheet2")

WorkSh.Activate

FilterRow = Rows("1:1").Find(What:="ID", LookAt:=xlWhole).Column

WorkSh.UsedRange.AutoFilter Field:=FilterRow, Criteria1:="="
End Sub

I should add that it would be best for you to explicitly refer to your range instead of using UsedRange

like image 187
dwirony Avatar answered Oct 21 '25 23:10

dwirony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!