• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Check if worksheet exists and delete it and then add it again

Waimea

New Member
Hi,

I am trying to automate the creation of a worksheet. I want to check if a file exists, if yes, delete the file, if no, create the file.

This is the code I currently have:

Code:
Dim sheet As Worksheet
Application.DisplayAlerts = False
Sheets("Test").Delete
Application.DisplayAlerts = True
Set sheet = Sheets.add
sheet.Name = "Test"
 
Hi,

See if this works for you. It loops thru the worksheet to see if it exist. If not it will add the sheet. This assumes you want a "Worksheet" and not a "File" as you indicated.
Code:
Sub sheet_Test()
Dim ws As Worksheet
For Each ws In Worksheets
    If ws.Name = "Test" Then
        Exit Sub
    Else
        Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Test"
    End If
Next ws
End Sub
 
Or you could just add On Error Resume Next...
Code:
Sub Demo()
Dim sheet As Worksheet
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Test").Delete
Application.DisplayAlerts = True
Set sheet = Sheets.Add
sheet.Name = "Test"
End Sub

But if you want to test if worksheet exists.
Use IsObject to check if worksheet is an object within the workbook.

https://chandoo.org/forum/threads/getting-vba-to-reference-the-correct-worksheet.12948/#post-76321

Ah! I left out the "Delete" if "Exist". Thank for the catch.
 
Back
Top