简体   繁体   中英

VBA - how to filter a table using a dynamic date range?

I have a macro that pulls a report from one worksheet, then pulls applicable data from another worksheet, and prints both pages to a single PDF file. The print to pdf side of it is working, but filtering the data to match the report is not.

I started with defining the start and end dates from the report, then I would like to filter the first column of my data worksheet based on this date range before printing.

My code is below:

Dim StartDate as Date, EndDate as Date, DataTable as String
EndDate = ActiveSheet.Range("G6")
StartDate = ActiveSheet.Range("G5")

Worksheets("Data").Activate
DataTable = Worksheets("Data").Range("A2").CurrentRegion.Address
ActiveSheet.Range(DataTable).AutoFilter Field:=1, Criteria1:=">=" & StartDate, Operator:=xlAnd, Criteria2:="<=" & EndDate

Changing the filter manually before running the macro does work, but I'd like for the macro to do it on its own. Any advice is much appreciated.

Try converting the dates into doubles when constructing the criteria strings:

ActiveSheet.Range(DataTable).AutoFilter Field:=1, _
   Criteria1:=">=" & CDbl(StartDate), Operator:=xlAnd, _
   Criteria2:="<=" & CDbl(EndDate)

Firstly, please get in the habit of being explicit with your sheet references – avoid using ActiveSheet and use the actual sheet name instead. The code below uses “Sheet2” to demonstrate this point. The code is tested and does work for me. Let me know how you go with it.

Option Explicit
Sub testFilter()
Dim StartDate As Date, EndDate As Date

StartDate = Sheets("Sheet2").Range("G5").Value2   <~~ **Change Sheet2 to your actual sheet name
EndDate = Sheets("Sheet2").Range("G6").Value2

With Sheets("Data").Range("A2").CurrentRegion
    .AutoFilter 1, ">=" & 1 * StartDate, 1, "<=" & 1 * EndDate
End With

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