ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Does a sheet exist (https://www.excelbanter.com/excel-programming/421255-does-sheet-exist.html)

Randall

Does a sheet exist
 
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

Dave Peterson

Does a sheet exist
 
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

Randall wrote:

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


--

Dave Peterson


All times are GMT +1. The time now is 05:18 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com