Does a sheet exist

R

Randall

Given a sheet name, I am trying to write some code that returns TRUE if a
sheet exists and FALSE if it does not.

Ex: SheetName = "Bob", Returns TRUE if there is a sheet by this name,
returns FALSE if it does not.

Thanks
 
D

Dave Peterson

You could use a function (from Chip Pearson) to test the existence of a sheet.

Function WorksheetExists(SheetName As Variant, _
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

'and you can use it like:
....
if worksheetexists("myname",activeworkbook) then

========
Lots of times, I'll just check with this kind of code:

Dim wks as worksheet
....
set wks = nothing
on error resume next
set wks = worksheets("somesheetname")
on error goto 0
if wks is nothing then
'not there
else
'it is there
end if
 

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

Top