Deleting Worksheets except for one, in Copy of workbook

KlaasE

New Member
Joined
Nov 4, 2019
Messages
37
Hello,

I'm am trying to make a copy of a workbook, which I then open and then I want to delete all sheets except for the sheet "OrderformulierKopie". The code I'm using right now keeps giving the error it is out of range (in the for loop). I can't figure out how to fix it.
Ivlgnr is made in another sub, defined like this: Ivlgnr = "DIS" & Format(Now(), "yy") & "-" & Format(volgnummer, "0000")

Any advice is welcome!
Code:
Private Sub cmdStart_Click()    
    mkFolder (ThisWorkbook.Path & "\" & Ivlgnr)
    Dim CopyNaam As String
    CopyNaam = ThisWorkbook.Path & "\" & Ivlgnr & "\" & Ivlgnr & ".xlsm"
    
    ActiveWorkbook.SaveCopyAs CopyNaam
    Application.Workbooks.Open CopyNaam
    
    Dim iterator As Long
    Application.DisplayAlerts = False
    For iterator = Workbooks(CopyNaam).Worksheets.Count To 1 Step -1
        With Workbooks(CopyNaam).Worksheets(iterator)
            If .CodeName <> "OrderformulierKopie" Then .Delete
        End With
    Next iterator
    Application.DisplayAlerts = True
    
    
    ThisWorkbook.Save
    End
End Sub
 
Last edited:
That shouldn't be possible - a workbook must contain at least one sheet.

It suggests that that is not in fact the code name of the sheet.
 
Upvote 0

Excel Facts

Save Often
If you start asking yourself if now is a good time to save your Excel workbook, the answer is Yes
And there was me thinking you could only directly refer to the codename in ThisWorkbook.

You can read the codename property, you just can't use the codename as a variable. (Well, you can, but only if you set a reference between the projects)
 
Upvote 0

Forum statistics

Threads
1,224,743
Messages
6,180,687
Members
452,994
Latest member
Janick

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