Deleate worksheet based on worksheet name

NichoD

Board Regular
Joined
Jul 31, 2022
Messages
54
Office Version
  1. 2016
Platform
  1. Windows
hello, I have a workbook with worksheets named after dates. I want to deleate all worksheets older than the first day of the last month. How would you suggest I do it? This is my current code.


Sub test()

Dim date1 As Date
Dim date2 As Date
Dim dd As Date
Dim ws As Worksheet

date1 = DateSerial(Year(Date), Month(Date) - 1, 1)
date2 = Date


For dd = date1 To date2
Debug.Print Format(dd, "YYMMDD")

Next dd

'For Each ws In Worksheets
'
'If not ws.Name = dd Then
' ws.Delete
' End If
'Next ws


End Sub
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
Hi there, If I got you right your worksheets names are like "DDMMYY".

Enjoy:

VBA Code:
Sub test()
    Dim firstDayOfPreviousMonth As Date
    Dim testDate As Date
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    firstDayOfPreviousMonth = DateSerial(Year(Date), Month(Date) - 1, 1)
    For Each Worksheet In ThisWorkbook.Worksheets
        testDate = DateSerial(CInt(Left(Worksheet.Name, 2)), CInt(Mid(Worksheet.Name, 3, 2)), CInt(Right(Worksheet.Name, 2)))
        If testDate < firstDayOfPreviousMonth Then
            Worksheet.Delete
        End If
    Next Worksheet
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,461
Messages
6,124,954
Members
449,198
Latest member
MhammadishaqKhan

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top