简体   繁体   English

如何使用变量自动过滤(WEEKNUM)

[英]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: 我将变量“ ThisWeek”设置为当前星期数:

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) 这将产生星期数,我正在过滤的列中有一个星期数列表(根据另一列中的日期显示WEEKNUM公式的结果)

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 . 我可以为AutoFilter提供的最佳方法是将TODAY()(在VBA中为Date )解析为开始日期和结束日期,然后将AutoFilter的Criteria1和Criteria2参数与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. 在VBA中,使用Weekday(<date>, [<optional vbDayOfWeek>])函数和一些小数学运算来查找上一个星期日(或任何其他DOW)和下一个星期六是一件小事。

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. Weekday和Date函数用于始终解析动态日期,例如5月的第二个星期日或11月的第三个星期一。

In VBA you have to use Date() instead of TODAY(), and to get the week's number, use DatePart() . 在VBA中,必须使用Date()而不是TODAY(),并且要获取星期数,请使用DatePart()

You have to check, how week numbers are counted in your country, and adapt parameter firstweekofyear of this function. 您必须检查一下,您所在国家/地区的周数是如何计算的,并调整此函数的firstweekofyear参数。

In Europe eg use DatePart("ww", Date, vbMonday, vbFirstFourDays) in VBA. 在欧洲,例如在VBA中使用DatePart("ww", Date, vbMonday, vbFirstFourDays)
The corresponding week number function in your worksheet is WEEKNUM(..., 21). 工作表中相应的星期数函数是WEEKNUM(...,21)。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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