首页 > 解决方案 > VBA Autofilter - 过滤掉比今天更旧的所有内容

问题描述

我有一些未来的数据,一旦根据昨天的日期过时,我需要过滤掉这些数据。我使用宏记录查看 ho 以按日期过滤掉,并使用代码制作了一个小脚本。

问题是当我自己从宏运行代码时,所有数据都被过滤掉了,而不是过时的。

     Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 1 To WS_Count

        ' Insert your code here.
        ' The following line shows how to reference a sheet within
        ' the loop by displaying the worksheet name in a dialog box.
        Set ws = ActiveWorkbook.Worksheets(I)
        A1 = ws.Range("A1").Value
        If (InStr(A1, "HEDGE POSITION") <> 0) And ws.AutoFilterMode = True Then

            Dat = CStr(Date - 1)
            datt = ">" & Dat
            MsgBox datt
            ws.Range("$A$4:$P$40").AutoFilter Field:=12, Criteria1:= _
            datt, Operator:=xlAnd
        End If

     Next I

所以这是宏记录器记录的代码。当我自己运行它时它不起作用(所有数据都消失了)

ActiveSheet.Range("$A$4:$P$40").AutoFilter Field:=12, Criteria1:= _
    ">16/12/2019", Operator:=xlAnd

编辑:

我注意到如果不是写“16/12/2020”而是写“12/16/2020”(交换月份和日期的位置),它会起作用

但我从 VBA 的日期函数中获取日期,我的日期格式为“日/月/年”。所以它应该适合 VBA 的 Date() 中的日期格式。

任何想法如何解决这一问题?

标签: excelvbafilterautofilter

解决方案


使用 Format 解决,[Dat = Format(Date, "mm/dd/yy")]:

     Dim WS_Count As Integer
     Dim I As Integer

     ' Set WS_Count equal to the number of worksheets in the active
     ' workbook.
     WS_Count = ActiveWorkbook.Worksheets.Count

     ' Begin the loop.
     For I = 1 To WS_Count

        ' Insert your code here.
        ' The following line shows how to reference a sheet within
        ' the loop by displaying the worksheet name in a dialog box.
        Set ws = ActiveWorkbook.Worksheets(I)
        A1 = ws.Range("A1").Value
        If (InStr(A1, "HEDGE POSITION") <> 0) And ws.AutoFilterMode = True Then


            Dat = Format(Date, "mm/dd/yy")

            datt = ">" & Dat

            ws.Range("$A$4:$P$40").AutoFilter Field:=12, Criteria1:= _
            datt, Operator:=xlAnd
        End If

     Next I

推荐阅读