简体   繁体   中英

Vba open workbook, apply filters and close workbook?

I am trying to use the following code to open an excel workbook, filter a column and close it again - saving changes.

Heres my code but for some reason it is not applying filters:

DisplayAlerts = False
OtherBook.Open
Selection.AutoFilter Field:=1, Criteria1:="49"
OtherBook.Close SaveChanges:=True

My workbook looks like this:

Column A and Column B already have filters applied/switched on in their headers.

Column A     Column B   <----(Filters On)
49           Dog
48           Cat 
49           Dog
47           Cat
49           Dog
45           Dog

Please can someone show me where i am going wrong?

'Selection' works on the active workbook, it's perhaps a little vague, maybe try referencing your range more precisely. Change this line:

Selection.AutoFilter Field:=1, Criteria1:="49"

To this:

Workbooks(OtherBook).ActiveSheet.Cells(1, 1).AutoFilter Field:=1, Criteria1:="49"

Or this:

Workbooks(OtherBook).ActiveSheet.Cells(1, 1).Resize(1, 2).AutoFilter Field:=1, Criteria1:="49"
Sub Filtertest()
Dim rangetofilter As Range
Dim lastrow As Long

  Application.ScreenUpdating = False
  Application.DisplayAlerts = False

  Workbooks("Calculator v1.2.xlsm").Worksheets("first").Range("dslist").ClearContents
  Workbooks.Open Filename:="C:\Users\username\Desktop\PPP\Test.xlsx"

  Set rangetofilter = Workbooks("Test.xlsx").Worksheets("copy4").Range("A1:F2586")
  rangetofilter.AutoFilter Field:=1, Criteria1:="marketing"

  lastrow = Workbooks("Test.xlsx").Worksheets("copy4").Cells(Workbooks("Test.xlsx").Worksheets("copy4").Rows.Count, "A").End(xlUp).Row
  Debug.Print lastrow

  Workbooks("Test.xlsx").Worksheets("copy4").Range("D2:D" & lastrow).Copy
  Workbooks("Calculator v1.2.xlsm").Worksheets("first").Range("A2").PasteSpecial Paste:=xlPasteValues

  Workbooks("Test.xlsx").Close False

  Application.ScreenUpdating = True
  Application.DisplayAlerts = True

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM