VBA自动筛选-筛选出比今天更旧的所有内容

问题描述 投票:0回答:1

我拥有一些将来的数据,因此我需要根据昨天的日期将其淘汰后将其过滤掉。我使用宏记录来查看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()中的日期格式。

任何想法如何解决此问题?

excel vba filter autofilter
1个回答
0
投票

通过使用格式解决,[日期=格式(日期,“ 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
© www.soinside.com 2019 - 2024. All rights reserved.