Home » excel » excel – Deleting worksheets by macro

excel – Deleting worksheets by macro

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to delete all sheets except the first sheet, but I get an

error 9 “subscript out of range” appears.

How can I fix it? Thanks in advance.

Dim Udalenie As Integer 
   If ThisWorkbook.Worksheets.Count > 1 Then
      For Udalenie = 2 To ThisWorkbook.Worksheets.Count
         ThisWorkbook.Sheets(Udalenie).Delete
   Next Udalenie
End If
How to&Answers:

Because each time you delete one sheet, the Excel will remove it from this sheet from Worksheets and the total sheets count will minus 1.

Dim Udalenie As Integer
If ThisWorkbook.Worksheets.Count > 1 Then
For Udalenie = 2 To ThisWorkbook.Worksheets.Count
ThisWorkbook.Sheets(2).Delete
Next Udalenie
End If