Delete specific number or sheets with VBA

DK340

New Member
Joined
Oct 13, 2009
Messages
17
I am trying to find macro coding that will delete worksheets automatically. For example, if I have a spreadsheet that has sheets 1 thru 50, I want to have the macro automatically find the last sheet (sheet 50) and count back until if finds sheet 31, then delete all sheets beyond sheet 31 (32-50 to be deleted). The number of sheets may vary from 50 to 40, but can a macro be written find the last sheet and delete all sheets above the 31st sheet?

Thanks
 

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.
Code:
Sub DeleteSheets()
    Dim lngLoop As Long
    
    If ThisWorkbook.Worksheets.Count > 30 Then
        Application.DisplayAlerts = False
        For lngLoop = ThisWorkbook.Worksheets.Count To 31 Step -1
            ThisWorkbook.Worksheets(lngLoop).Delete
        Next lngLoop
        Application.DisplayAlerts = True
    End If
    
End Sub
 
Upvote 0
This works great but I do have one more question. I want to use this as a personal macro so that I can use it on random pages, not specific to one workbook. When I try this as a personal macro it doesn't work. Do you know the fix?
 
Upvote 0

Forum statistics

Threads
1,214,430
Messages
6,119,443
Members
448,898
Latest member
drewmorgan128

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