I am currently working on a VBA macro, that takes data from a Worksheet and copies it to another. If the destination Worksheet does not exist it should create it and than write the data from my array.
Problem:
I have a function to test if the worksheet already exists.
If it is the case my macro will successfully write the data i want. But if the worksheet doesnt exist VBA is displaying the error you can see below.
In the list Workbook.Worksheets is no Sheet named like this but I get that error anyway.
Here is my relevant code:
(If something is missing for understanding the problem I can fill in the missing part in too)
Function sheetExists(sheetToFind As String) As Boolean
Dim Sheet As Worksheet
For Each Sheet In Worksheets
If sheetToFind = Sheet.Name Then
sheetExists = True
Exit Function
End If
Next Sheet
sheetExists = False
End Function
In my main Sub I used this code:
If sheetExists("SheetName") = False Then
Dim newSheet As Worksheet
With ThisWorkbook
.Sheets.Add(After:=Worksheets(Worksheets.Count)).Name = "SheetName"
End With
End If
The exact error:
1004 Cannot rename a sheet to the same name as another sheet, a reference object library, or a workbook referenced by Visual Basic
First it was executing successfully but after I deleted the sheet manually the error occurred.
Thanks for any help :)
For Each Sheet In ThisWorkbook.Worksheets
- PᴇʜIf sheetExists("SheetName") = False
withIf Not sheetExists("Sheetname")
. - AntiDrondertOn Error Resume Next
, try and set a reference to the worksheetSet Sheet=ThisWorkbook.Worksheets(sheetToFind)
and then see if an error occurred -sheetExists = (Err.Number = 0)
. - Darren Bartrup-Cook