• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

VBA code to filter as per date

Hi,

I have this code which works perfect. However I now have about 40files and each file will have different start dates. Do I have to go to each file and specify the start date in the range for this code to pick up or is there another way around?

Code:
Public Sub MyFilter()
    Dim lngStart As Long, lngEnd As Long
    lngStart = Range("AA4").Value 'assume this is the start date
    lngEnd = Range("AA5").Value 'assume this is the end date
    Range("E:E").AutoFilter field:=1, _
        Criteria1:=">=" & lngStart, _
        Operator:=xlAnd, _
        Criteria2:="<=" & lngEnd
      
End Sub

Regards,
Sameer
 
I don't really understand exactly what you are trying to do, but it sounds like you don't want to type dates into AA4 and AA5 each time you run your macro on a new workbook.
You could replace the cell references with an input box (google vba inputbox) so that you can type the dates in a pop-up, but that is almost the same thing.
A simple solution might be to have another workbook open whilst you go through your process, which has a list of file names and dates in columns. If filename was in column A, start date in column b and end date in column c, all in sheet 1, in a workbook called "Dates" then you could do this:
Code:
Public Sub MyFilter()
    Dim lngStart As Long, lngEnd As Long, rownum As Integer
    rownum = Application.WorksheetFunction.Match(ActiveWorkbook.Name, Workbooks("Dates").Sheets("Sheet 1").Range("A:A"), 0)
    lngStart = Workbooks("Dates").Sheets("Sheet 1").Range("B" & rownum).Value 'read start date from Dates workbook
    lngEnd = Workbooks("Dates").Sheets("Sheet 1").Range("C" & rownum).Value  'read end date from Dates workbook
    Range("E:E").AutoFilter field:=1, _
        Criteria1:=">=" & lngStart, _
        Operator:=xlAnd, _
        Criteria2:="<=" & lngEnd
     
End Sub

... or something similar.

I hope this helps.
 
Sorry for the delay @Stevie

This code runs however excludes current date.

Code:
Range("E:E").AutoFilter field:=1, _
        Criteria1:=">=" & lngStart, _
        Operator:=xlAnd, _
        Criteria2:="<=" & lngEnd
 
Sameer.k21

Check Something like this!!

Tested!!!

Code:
Dim lngStart As Date, lngEnd As Date

lngStart = Format(DateSerial(2015, 10, 23), "YYYY-MM-DD")

lngEnd = Format(DateSerial(2016, 1, 4), "YYYY-MM-DD")

Range("E:E").AutoFilter field:=1, _
        Criteria1:=">=" & lngStart, _
        Operator:=xlAnd, _
        Criteria2:="<=" & lngEnd
 
Back
Top