VBA to add sheet; with name; after checking first

D

Dennis

XL 2003 & 97

Almost have it. (I think)

My "If Not" syntax below is incorrect.
The middle line works fine.

If Not Sheets.Name("New") Then
Sheets.Add.Name = "New"
End If

The code is to
1) check the workbook for a sheet name first
2) If the sheet does not exist then add a sheet
3) Name the sheet "New"

Is there a better way?

TIA Dennis
 
D

Dave Peterson

Chip Pearson posted a nice function that you can use (especially nice if you
have to this lots of places in your code):

Option Explicit
Sub testme()
If WorksheetExists("New", ActiveWorkbook) Then
'do nothing
Else
ActiveWorkbook.Worksheets.Add.Name = "New"
End If
End Sub

Function WorksheetExists(SheetName As String, _
Optional WhichBook As Workbook) As Boolean
'from Chip Pearson
Dim WB As Workbook
Set WB = IIf(WhichBook Is Nothing, ThisWorkbook, WhichBook)
On Error Resume Next
WorksheetExists = CBool(Len(WB.Worksheets(SheetName).Name) > 0)
End Function
 
Top