【问题标题】:Excel VBA Datetime Filter Hides All Rows Except Top RowExcel VBA日期时间过滤器隐藏除顶行之外的所有行
【发布时间】:2019-07-12 13:36:27
【问题描述】:

我每周都会收到一个不断增长的数据集,并且必须仅过滤过去 7 天的内容(从上周上午 11:00 开始每周更新)。我想通过 VBA 自动化整个过程,但我正在努力让日期时间自动过滤器工作。日期时间列如下所示(dd-mm-yyyy 时间):

我在 VBA 中设置了一个自动过滤器,代码如下:

Dim d1, d2, m1, m2, y1, y2 As Integer
Dim dt1, dt2 As String
d1 = Day(Date - 7)
d2 = Day(Date)
m1 = Month(Date)
y1 = Year(Date)
dt1 = d1 & "." & m1 & "." & y1
dt2 = d2 & "." & m1 & "." & y1

ActiveSheet.Range("$A$1:$CZ$99999").AutoFilter Field:=57, Criteria1:= _
    ">=" & dt1 & " 11:00", Operator:=xlAnd, Criteria2:="<=" & dt2

如果我让代码在工作表上运行,它将应用过滤器,但将整个工作表留空,除了顶行,如下所示:

当我现在在 EXCEL 中手动输入自动过滤器功能以检查应用了哪种过滤器时,它会完全按照我的意愿显示过滤器,并在按下“确定”时它实际应用并显示正确的值:

所以代码确实插入了正确的过滤器,但将所有单元格留空,直到我在过滤器功能中手动按“确定”。 如何解决此问题,以便代码正确应用自动过滤器并自动显示值?

我发现这个问题似乎与EXCEL国家版本有关。我正在使用德语excel,设置为英语。但我不知道这意味着什么以及如何解决这个问题。

提前感谢您的帮助。

【问题讨论】:

  • 如果您单击过滤器的下拉菜单,它究竟表示它正在过滤的是什么
  • 没有勾选框 --> “日期过滤器”后面的检查 --> “Between”.. --> 如果我点击它会显示正确的日期+时间(放一张图片这个问题,所以你可以看到)

标签: excel datetime filter excel-formula excel-2010


【解决方案1】:
dt1 = d1 & "." & m1 & "." & y1
dt2 = d2 & "." & m1 & "." & y1

这些不是Dates。您无法将它们与Dates 进行比较。

ActiveSheet.Range("$A$1:$CZ$99999").AutoFilter Field:=57, Criteria1:= _
    ">=" & dt1 & " 11:00", Operator:=xlAnd, Criteria2:="<=" & dt2

现在尝试过滤等于String"5.7.2019 11:00" 等于String"12.7.2019"Date 值。因为"5.7.2019 11:00" 不等于"12.7.2019",所以它永远不会是True。由于Date的值不是String的值,所以会更少True

当您手动打开过滤器菜单时,它包含文本"12.7.2019""5.7.2019 11:00"。当您单击“确定”时,它会解析这些内容,识别出它们假定是日期,并将它们转换为Dates。然后就可以了。

您需要做的是在使用之前将您的Strings 转换为Dates。我们还需要解决 Microsoft Office 以美国为中心的习惯,即认为“12.7.2019”意味着“7th December 2019”而不是“12th July 2019”:

'VBA uses the same memory for Integer and Long, so always use Long
Dim d1 As Long, d2 As Long, m1 As Long, m2 As Long, y1 As Long, y2 As Long
'EVERY item on the row needs to be declared, not just the last one
'Any items without an "As" will default to Variant
Dim dt1 As Date, dt2 As Date

'Date is a horrible choice for a Variable name, because it is a built in Type
d1 = Day(Date - 7)
d2 = Day(Date)
m1 = Month(Date)
y1 = Year(Date)
'You forgot m2 and y2.  Very important on the 3rd January
m2 = Month(Date-7)
y2 = Year(Date-7)

'
dt1 = DateSerial(y1, m1, d1)
dt2 = DateSerial(y2, m2, d2)

'Why not just use entire columns "$A:$CZ"?
ActiveSheet.Range("$A$1:$CZ$99999").AutoFilter Field:=57, Criteria1:= _
    ">=" & cDbl(dt1 + TimeSerial(11,0,0)), Operator:=xlAnd, Criteria2:="<=" & cDbl(dt2)

【讨论】:

  • 感谢 Chronocidal 的帮助、提示和很好的解释。不幸的是,它似乎仍然不起作用。 (7 天前)日期现在显示这个数字:436514583333333... 而另一个是正确的。有什么想法吗?
猜你喜欢
  • 2020-11-12
  • 1970-01-01
  • 2016-11-19
  • 2014-06-01
  • 2018-10-27
  • 2017-05-28
  • 2012-12-24
  • 1970-01-01
  • 2017-04-10
相关资源
最近更新 更多