简体   繁体   中英

Extracting data between to dates and paste to new sheet

I have some excel files which each contain 3 rows of data for each single day of the year (date (A1), AVG (B1), CV (C1)) for last 30 years. Now, I want to divide them by the year that they've been collected (eg last 20 years, last 10 years, last year, or even last 6 months). So, I use few lines to put the start and end date in two cells and filter out the data (cells) between these two dates.

Dim lngStart As Long, lngEnd As Long
lngStart = Range("E1").Value 'assume this is the start date
lngEnd = Range("E2").Value 'assume this is the end date
Range("A2:A4000").AutoFilter field:=1, _
    Criteria1:=">=" & lngStart, _
    Operator:=xlAnd, _
    Criteria2:="<=" & lngEnd

`

And add few more lines to copy those data to a new sheet.

`Range("A1:C1").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Paste´

But, I have several of these worksheets and I have to make a separate sheet for last 30years, 20y, 10y, 5y, 3y, 1y, 6months, 3m and 1month in each worksheet. I wonder if is there any chance to have a macro to extract all these time periods (eg last 10y according to the last date in database) and copy them to the new sheet labeled by its own specific time period (eg "10y")at once!? So, the results would be 9 new labeled sheets, each with three columns (date (A1), AVG (B1), CV (C1))! Sorry for the long story :)
Thanks a lot for your help, and looking forward to hearing from you guys!

Best, Neos116

Morpheus : I'm trying to free your mind, Neo. But I can only show you the door. You're the one that has to walk through it.

So let's look what we got here... 1 spoon of "Adding new Sheet on the fly":

    ActiveWorkbook.Sheets.Add Before:=Worksheets(Sheets.Count)
    ActiveSheet.Name = "blabla"

A cup of "Finding the Edge":

i=2 'Assuming your first row contains column names
Do While CDate(Cells(i, "A")) >= DateAdd("m", Now, -1) 'to get last month dates only
    i = i + 1
loop
'At this point i holds the row number of the very first record earlier then last 1 month

And just a little bit of "Copy&Paste your Range":

Range(Cells(2, "A"), Cells(i-1, "C")).Copy
Sheets("1m").Select
Cells(2, "A").PasteSpecial xlPasteAll

You get the recipe, you got an ingredients, now try to cook something yourself.

Good luck! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM