Using cell values as a date range autofilter

2019-09-12 17:19发布

I'm trying to adjust my date autofilter with a range extracted from 2 cells.

After some failed tries, I decided to do the macro with the macro builder so I could tweak it to adust to my code, and I ended up with:

Dim fI As Range
Dim fF As Range

Set fI = Worksheets("Sheet1").Range("B26")

Set fF = Worksheets("Control").Range("B27")


    ActiveSheet.ListObjects("TABLE_REPORTS_GENERAL_INFO").Range _
        .AutoFilter Field:=24, Criteria1:=fI.Value, Operator:=xlAnd, _
        Criteria2:=fF.Value

The dates are in the correct format, but it will just let the filter clean. Hardcoding the dates is working, what am I doing wrong?

My dates structure:

Starting Date   01/08/2015
Last Date   31/07/2016

2条回答
小情绪 Triste *
2楼-- · 2019-09-12 17:42

I've noticed that you are in a DMY date format. I will try to keep to that regional standard.

Use an array with data types as Criteria2.

With ActiveSheet
    With .ListObjects("TABLE_REPORTS_GENERAL_INFO")
        .Range.AutoFilter Field:=13, Operator:=xlFilterValues, _
            Criteria2:=Array(2, Format(fi.Value, "d/m/yyyy"), 2, Format(ff.Value, "d/m/yyyy"))
    End With
End With

That should filter for the two dates. However, if you want all the dates between a start date and an end date then you need to introduce operators.

With ActiveSheet
    With .ListObjects("TABLE_REPORTS_GENERAL_INFO")
        .Range.AutoFilter Field:=13, _
            Criteria1:=Format(fi.Value, "\>\=d/m/yyyy"), Operator:=xlAnd, _
            Criteria2:=Format(ff.Value, "\<\=d/m/yyyy")
    End With
End With
查看更多
乱世女痞
3楼-- · 2019-09-12 18:05

You are assigning your second range to fechaFin, but later you only use fF, so try assigning your range like this: Set fF = Worksheets("Control").Range("B27")

Because right now fF.Value is an empty string, which will probably reset the filter

查看更多
登录 后发表回答