Test if sheet exits, create with name if not

  • Thread starter Thread starter bramweisman
  • Start date Start date
B

bramweisman

I have some code that successfully imports data into worksheets. I hav
a variable HOTSHEET that contains the text string from a certain cell.
How can I test to see if this sheet exits, and if not create one wit
the proper name. I saw Tom Oglvy's response to Steph on a simila
subject but couldn't really make sense of it in this context
 
Hi Bram

Copy the function and the macro in a normal module

Function SheetExists(sname As String, _
Optional ByVal WB As Workbook) As Boolean
'Chip Pearson
On Error Resume Next
If WB Is Nothing Then Set WB = ThisWorkbook
SheetExists = CBool(Len(WB.Sheets(sname).Name))
End Function

Sub Test()
Dim HOTSHEET As String
HOTSHEET = "test"
If SheetExists(HOTSHEET) = False Then
Sheets.Add.Name = "test"
Else
'do nothing
End If
End Sub
 
One way

Sub CreateIt()

If Not SheetExists("mySheet") Then
Worksheets.Add.Name = "mySheet"
End If

End Sub

'-----------------------------------------------------------------
Function SheetExists(Sh As String, _
Optional wb As Workbook) As Boolean
'-----------------------------------------------------------------
Dim oWs As Worksheet
If wb Is Nothing Then Set wb = ActiveWorkbook
On Error Resume Next
SheetExists = CBool(Not wb.Worksheets(Sh) Is Nothing)
On Error GoTo 0
End Function
 
Oops

Use this

Sheets.Add.Name = HOTSHEET


--
Regards Ron de Bruin
http://www.rondebruin.nl


Ron de Bruin said:
Hi Bram

Copy the function and the macro in a normal module

Function SheetExists(sname As String, _
Optional ByVal WB As Workbook) As Boolean
'Chip Pearson
On Error Resume Next
If WB Is Nothing Then Set WB = ThisWorkbook
SheetExists = CBool(Len(WB.Sheets(sname).Name))
End Function

Sub Test()
Dim HOTSHEET As String
HOTSHEET = "test"
If SheetExists(HOTSHEET) = False Then
Sheets.Add.Name = "test"
Else
'do nothing
End If
End Sub
 
try this. It will make it if if does not exist.

Sub namenewsheet()
Dim ns As Worksheet
myname = "mynewsheetname"
'myname=range("d1").value
On Error Resume Next
Set ns = ActiveWorkbook.Worksheets(myname)
On Error GoTo 0
If sht Is Nothing Then Sheets.Add.Name = myname
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top