Excel Macro to Filter Column to Today's Date

旧时模样 提交于 2021-01-29 06:15:41

问题


I have a list of dates in column J of my workbook which I would like to have a macro that will automatically filter to only show those rows with today's date in column J.

Also, it would be awesome if I can have the code to filter column J by the date referenced in cell K1.

Could anyone kindly help me out with the code for both? Any guidance would be greatly appreciated!

Here is the code when I recorded my macro to manually select today's date in column J:

Sub Filter_Today()
'
' Filter_Today Macro
' Filter date column for today's date.
'

'
    ActiveSheet.Range("$A$5:$K$3416").AutoFilter Field:=10, Operator:= _
        xlFilterValues, Criteria2:=Array(2, "9/14/2018")
End Sub

回答1:


You can filter for today (dynamic) by using the special date filters.

Sub Filter_Today()

    with worksheets("sheet1")
        with .range(.cells(5, "J"), .cells(.rows.count, "J").end(xlup))
            .autofilter field:=1, criteria1:=xlFilterToday, operator:=xlFilterDynamic
        end with
    end with

end sub

Filter on the value in K1 using a more conventional AutoFilter.

Sub Filter_K1()

    With Worksheets("sheet1")
        With .Range(.Cells(5, "J"), .Cells(.Rows.Count, "J").End(xlUp))
            .AutoFilter Field:=1, Criteria1:=Format(.Parent.Range("K1").Value, "=mm/dd/yy")
        End With
    End With

End Sub

The date formatting should match the date formatting used in column J.



来源:https://stackoverflow.com/questions/52340156/excel-macro-to-filter-column-to-todays-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!