title: VBA create new Worksheet if not exists
body: <p>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.</p>
  
  <p><strong>Problem:</strong><br>
  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.</p>
  
  <p><strong>Here is my relevant code:</strong><br>
  (If something is missing for understanding the problem I can fill in the missing part in too)</p>
  
  <pre><code>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
  </code></pre>
  
  <p>In my main Sub I used this code:</p>
  
  <pre><code>If sheetExists("SheetName") = False Then
      Dim newSheet As Worksheet
      With ThisWorkbook
          .Sheets.Add(After:=Worksheets(Worksheets.Count)).Name = "SheetName"
      End With
  End If
  </code></pre>
  
  <p><strong>The exact error:</strong></p>
  
  <blockquote>
    <p>1004 Cannot rename a sheet to the same name as another sheet, a reference object library, or a workbook referenced by Visual Basic</p>
  </blockquote>
  
  <p>First it was executing successfully but after I deleted the sheet manually the error occurred.</p>
  
  <p>Thanks for any help :)</p>