search for worksheet, insert new if doesn't exist

  • Thread starter Thread starter cereldine
  • Start date Start date
C

cereldine

Im opening up a workbook and then selecting a worksheet based on
string variable like so (wsI is worksheet variable, sYear is searc
criteria)

Set wsI = Sheets(sYear)

I would like to improve this so that if the worksheet does not exist
insert a new one and then rename it to my search variable, i though
something along the lines of the below would work but it hasn't!
guess the 0 is the wrong thing to look for, any help appreciated

If Sheets(sYear) = 0 Then
Sheets.Add
ActiveSheet.Name = sYear
Else
Set wsI = Sheets(sYear)
End I
 
Here is a function that tells you if a sheet exists in a given workbook

Public 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

If sheetexists(sYear) Then
Set wsI = Sheets(sYear)
Else
Sheets.Add
Set wsI = Activesheet
wsI.Name = sYear
End If
 
On Error Resume Next
Set wsI = Worksheets(sYear)
On Error GoTo 0
If wsI Is Nothing Then
Worksheets.Add.Name = sYear
Set wsI = Worksheets(sYear)
End If

--
HTH

Bob Phillips

(remove nothere from email address if mailing direct)
 

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