Excel VBA自动过滤器不能使用Date列 [英] Excel VBA Autofilter not working with Date column

查看:245
本文介绍了Excel VBA自动过滤器不能使用Date列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



它在普通过滤器中运行良好,但过滤日期列无法正常工作。
列被格式化为日期,我可以手动和荒谬地过滤它,如果我运行我的代码,它只过滤器,但是当我检查过滤器,然后只是单击确定(没有更改应用于过滤器条件),它开始正确过滤。



这是我的代码:

  ws .ListObjects(SheetName).Range.AutoFilter字段:= 3,Criteria1 _ 
:=> & CDate([datecell]),Operator:= xlAnd,Criteria2:= _
< =& CDate(WorksheetFunction.EoMonth([datecell],3))

任何人都有想法?这似乎是一个常见的问题,但我没有找到解决方案。



提前感谢。



编辑:只要添加,当我的宏记录它并运行记录的宏,它也不起作用。

解决方案

日期可以使用Excel VBA AutoFilter非常棘手。有些人发现只需循环通过要过滤的数组。



有时我发现可以使用日期的数字值,特别是在处理日期之间

  Criteria1:=> & CDbl([datecell])
Criteria2:=< =& CDbl(WorksheetFunction.EoMonth([datecell],3))

请注意,以上需要真实日期,而不是日期的字符串。即使是一个单一的字符串日期也会使事情变得困难。


I got a problem using AutoFilter with VBA in Excel.

It works well for regular filters, but filtering the date column does not work as intended. The column is formatted as date, I can filter it manually and absurdly, if I run my code, it filters nothing but when I check the filter and then only click ok (no change being applied to the filter criteria), it starts filtering correctly.

Here is my code:

ws.ListObjects(SheetName).Range.AutoFilter Field:=3, Criteria1 _
        :=">" & CDate([datecell]), Operator:=xlAnd, Criteria2:= _
        "<=" & CDate(WorksheetFunction.EoMonth([datecell], 3))

Anyone has an idea? It seems to be a common problem, but I have not found a solution.

Thanks in advance.

Edit: Just to add, when I macro record it and run the recorded macro, it does not work either.

解决方案

Dates can be tricky with Excel VBA AutoFilter. Some find it easier to just loop through the array to be filtered.

Sometimes I have found that one can use the numeric value of the date, especially when dealing with "dates between"

Criteria1:= ">" & CDbl([datecell])
Criteria2:= "<=" & CDbl(WorksheetFunction.EoMonth([datecell], 3))

Note that the above need to be "real dates" and not strings that look like dates. Even a single "string date" will mess things up.

这篇关于Excel VBA自动过滤器不能使用Date列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆