Link to home
Start Free TrialLog in
Avatar of Sandra Smith
Sandra SmithFlag for United States of America

asked on

Delete worksheets based on a for next loop not working

I have the below, I have an Excel workbook that has up to 25 worksheets.  The code brings in information from a database and depending on the product, anywhere from 1 to 25 of the worksheets are used, that is, the code changes the name of hte worksheet from just, say, "1" to "Lipstick".  However, if not all of the worksheets are used, I need to delete those that still have their "number".  The sheets are named 1 to 25 before being used (I did not set up this workbook, it is inherited)  So.  I need to stream line and delete the extra workbooks, but I simply cannot get the below to work.  I keep getting a subscript out of range error message.

Public Sub DeleteUnused()
Dim ws As Worksheet, i As Integer
i = 25
 
For i = 25 To 1 Step -1
    If Worksheets(i).Name = Worksheets(" & i & ") Then
        Worksheets(" & i & ").Delete
    End If
Next i
    
End Sub

Open in new window

SOLUTION
Avatar of zorvek (Kevin Jones)
zorvek (Kevin Jones)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sandra Smith

ASKER

Wow!  All three were good and worked!  So I am going to split the points, but give the larger portion to Brian as this was the one I actually used.  Thank you all!
Avatar of bkenny_ie
bkenny_ie

good man - cheers!

B