So I've made a piece of code to copy an existing sheet into a new sheet and name it, based on some options chosen in the original sheet.
The problem is that if a sheet named "Example 1" already exists, and the original sheet is asked to create a new sheet and name it "Example 1" then the program runs into an error.
I've tried to get around this problem by adding a loop that checks all the worksheets for the given name, and if it exists asks the user if it should be deleted or not.
If the user wants it deleted, then it is deleted and a new version of the sheet is created with the same name. If not, then the program ends.
That alone works fine and dandy, but if the program does NOT find a sheet with the same name as the one I'm creating, then nothing happens.
The code is as follows
Sub TestForArk()
'Modul til at kopiere Indleveringsplanen som den er, og gøre det nye ark uafhængigt af ændringer i Indleveringsplanen
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Sheets("Indleveringsplan").Unprotect
'Låser op for indleveringsplanen
For Each ws In wb.Worksheets
If ws.Name = "Indleveringsplan (2)" Then
Application.DisplayAlerts = False
Sheets("Indleveringsplan (2)").Delete
Application.DisplayAlerts = True
End If
Next
Sheets("Indleveringsplan").Copy Before:=Sheets(2)
'Kopierer indleveringsplanen for at få den rette opsætning
For Each ws In wb.Worksheets
If ws.Name = ("Indleveringsplan " & Range("L3")) Then
If MsgBox("Der findes allerede et ark for det valgte produkt, ønsker du at slette det gamle ark og oprette et nyt?", _
vbYesNo, "Ark med samme navn fundet") = vbYes Then
Application.DisplayAlerts = False
Sheets("Indleveringsplan " & Range("L3")).Delete
Application.DisplayAlerts = True
Module1.Kopier_Ark
Else
Application.DisplayAlerts = False
Sheets("Indleveringsplan (2)").Delete
Application.DisplayAlerts = True
MsgBox "Arket blev ikke oprettet", Title:="Handling Annuleret"
End If
End If
Next
Sheets("Indleveringsplan").Protect
'Låser indleveringplanen igen
End Sub
I realise that nothing happens because I haven't added any code for it to do so, but all my attempts so far have resulted in errors or screwed up what worked before.
This is my most functional attempt so far.