简体   繁体   中英

How to Autofilter using a variable (WEEKNUM)

I am trying to create a macro which filters a table according to the current week number.

I've set the variable 'ThisWeek' to give me the current week number:

Dim ThisWeek As Variant

ThisWeek = "=WeekNum(TODAY())"

This produces the week number, and the column I'm filtering has a list of week numbers (displaying the result of a WEEKNUM formula according to dates in another column)

However I cant get the criteria to accept the variable with the following code:

Sheet2.ListObjects("Table3").Range.AutoFilter Field:=10, Criteria1:=ThisWeek

I've searched around the web for a couple hours now and tried lots of variables including:

Sheet2.ListObjects("Table3").Range.AutoFilter Field:=10, Criteria1:=">=" & ThisWeek, Operator:=xlAnd, Criteria2:="<=" & ThisWeek

I've tried changing the variable type to integer also..

But no luck.. any help hugely appreciated!

Thanks

The best method I can come with for AutoFilter would be to resolve the TODAY() ( Date in VBA) to the start and end date then use AutoFilter's Criteria1 and Criteria2 arguments with Operator:=xlAnd . Finding the previous Sunday (or any other DOW) and next Saturday is a small matter in VBA using the Weekday(<date>, [<optional vbDayOfWeek>]) function with some small math.

The Weekday and Date functions are used to resolve dynamic dates like the second Sunday in May or the third Monday in November all the time.

In VBA you have to use Date() instead of TODAY(), and to get the week's number, use DatePart() .

You have to check, how week numbers are counted in your country, and adapt parameter firstweekofyear of this function.

In Europe eg use DatePart("ww", Date, vbMonday, vbFirstFourDays) in VBA.
The corresponding week number function in your worksheet is WEEKNUM(..., 21).

Dim ThisWeek As Integer
ThisWeek = DatePart("ww", Date, vbMonday, vbFirstFourDays)
Sheet2.ListObjects("Table3").Range.AutoFilter Field:=10, Criteria1:=ThisWeek

也可以对其进行评估 (不确定是否需要使用"=" &部分):

ThisWeek = "=" & [WeekNum(TODAY())]

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