Date filter on Excel VBA

I have searched all over the web and I couldnt find anything that could properly help me with a code.

What I need is simple, but I still couldnt find it.

*The situation --> Everyday, in my company, we receive a sales report accumulated by the actual month. As I have my own workbook, everyday I gotta filter only the information that I need and paste it on my workbook. When it's monday we receive the information from friday and saturday sales together. I'm trying to code something to filter only yesterday, if it's not monday, and to filter friday and saturday, in case it's monday.

COLUMN D Contains the DATE I want to filter

As today is Thursday, I have set the if condition to vbthursday in order to test.

sabado = saturday; friday = sexta;

Sub Data()
Dim yesterday As String


If Weekday(Date, vbThursday) = 1 Then

Dim sabado As String
Dim sexta As String
Range("D1").Select
Selection.AutoFilter
sabado = Format(Date - 2, "dd/mm/yyyy")
sexta = Format(Date - 3, "dd/mm/yyyy")

ActiveSheet.Range("$A$1:$E$11").AutoFilter Field:=4, Operator:= _
xlFilterValues, Criteria1:="=" & sabado, Criteria2:="=" & sexta



Else

Range("D1").Select
Selection.AutoFilter
yesterday = Format(Date - 1, "dd/mm/yyyy")
ActiveSheet.Range("$A$1:$E$11").AutoFilter Field:=4, Operator:= _
xlFilterValues, Criteria1:="=" & yesterday



End If

Actualy the if condition is working, it recognizes when it's vbMonday (in the test case, vbThursday) and when it's not. The else condition is also working too and it filters just as it should filter. The problem is that, when the macro enters the if condition, it does not filter properly. It runs throught the end and does not accuse any errors.

Somebody help :(

1 answer

  • answered 2018-10-11 19:35 BigBen

    How about something like this?

    Sub Data()
        Dim datesToFilter()
    
        If Weekday(Date, vbMonday) = 1 Then
            datesToFilter = Array(Date - 2, Date - 3)
        Else
            datesToFilter = Array(Date - 1)
        End If
    
        ActiveSheet.Range("$A$1:$E$11").AutoFilter Field:=4, Operator:= _
        xlFilterValues, Criteria1:=datesToFilter
    
    End Sub