Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can you Delete Worksheets based on oldest and count ? 2

Status
Not open for further replies.

ljsmith91

Programmer
Joined
May 28, 2003
Messages
305
Location
US
I have a macro that we execute periodically and creates a new worksheet in a workbook with a date for each sheet name that is the date the macro last ran. The problem is that over time we end up retaining too many worksheets. We only need the last 5 or so. How can I include in the macro a process for pruning the oldest worksheets and keeping only the last 5 ? Is this possible ?

Any help or direction would be great.
 
Hi ljsmith91,

This will create a new sheet with the date as a name and then run through all the other sheets looking for the one whose name is the earliest date in the same format - you can probably adapt it to your own needs
Code:
SheetName = Date
SheetNameFormat = "dd MMM yyyy"
With ActiveWorkbook
    .Worksheets.Add.Name = Format(SheetName, SheetNameFormat)
    For Each Sheet In .Sheets
        If DateValue(Sheet.Name) < SheetName Then
            SheetName = DateValue(Sheet.Name)
        End If
    Next
    Application.DisplayAlerts = False
    Sheets(Format(SheetName, SheetNameFormat)).Delete
    Application.DisplayAlerts = True
End With

Enjoy,
Tony

--------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading this: Before you ask a question.
Excel VBA Training and more Help at VBAExpress[
 
TonyJollans,

Thanks so much. That is helpful in determining how to remove those sheets older than a specific date. I can use that. I still need to be able to prune based on how many sheets there are also. I only want to keep 5 sheets regardless of their dates. Is this possible ?

Thanks.
 
You can use:

Code:
Do Until ActiveWorkbook.Sheets.Count = 5
Loop
In conjunction with Tony's code
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top