deleting sheets in vba - subscript out of range msg

lezawang

Well-known Member
Joined
Mar 27, 2016
Messages
1,805
Office Version
  1. 2016
Platform
  1. Windows
Hi
I want to delete all the sheets in a workbook except the first one. I wrote the code below but what is the problem, It deleted some but then I got message "subscript out of range". I think because I do not have 40 sheets (my For loop is from 2 to 40). I do not know how many sheets in the file. I want to delete them no matter how many. Is that possible? thank you.


Sub delelesheets()
Dim x As Integer
For x = 2 To 4
ThisWorkbook.Worksheets(x).Delete
Next
End Sub
 

Excel Facts

What is the fastest way to copy a formula?
If A2:A50000 contain data. Enter a formula in B2. Select B2. Double-click the Fill Handle and Excel will shoot the formula down to B50000.
Try:
Code:
[COLOR=#333333]For x = 2 To Worksheets.Count[/COLOR]
 
Upvote 0
Try:
Code:
Sub delelesheets()
    Application.DisplayAlerts = False
    Do While Worksheets.Count > 1
        Worksheets(Worksheets.Count).Delete
    Loop
    Application.DisplayAlerts = True
End Sub
 
Upvote 0
One more code:
Rich (BB code):
Sub DeleteExtraSheets()
  If Sheets.Count = 1 Then Exit Sub
  Application.DisplayAlerts = False
  Sheets(Evaluate("TRANSPOSE(ROW(2:" & Sheets.Count & "))")).Delete
  Application.DisplayAlerts = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,179
Members
453,021
Latest member
Justyna P

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