Delete Multiple Sheets

sfran

New Member
Joined
Mar 9, 2021
Messages
28
Office Version
  1. 365
Platform
  1. Windows
Hello..

I am trying to delete all sheets after sheet 7 but getting errors. From what I am seeing, some sheets do get deleted, but not sequentially (not that I care on sequence, but just an observation) and then I get a Run-time error '9' Subscript out of range error.

I start off with having several sheets hidden that I unhide to make cycling through the sheets easier. Then starting with sheet 7, I want do delete all sheets.

If I run through this several times, eventually all the sheets (starting with sheet 7 on) do get deleted, but I cannot understand what I am doing wrong. My code is as follows:

Dim i As Long
Dim WS As Worksheet

For Each WS In Worksheets
WS.Visible = True
Next

totalsheets = Worksheets.Count

Application.DisplayAlerts = False
For i = 7 To totalsheets
Sheets(i).Delete
Next i



Any guidance would be appreciated

Thank you!
 

Excel Facts

Does the VLOOKUP table have to be sorted?
No! when you are using an exact match, the VLOOKUP table can be in any order. Best-selling items at the top is actually the best.
You need to loop backwards like
VBA Code:
For i = totalsheets to 7 step -1
 
Upvote 0
Solution
Glad to help & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,215,043
Messages
6,122,825
Members
449,096
Latest member
Erald

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