ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Worksheet Exists... (https://www.excelbanter.com/excel-programming/278839-worksheet-exists.html)

James Weaver

Worksheet Exists...
 
How do you find out if a worksheet exists or not within a
workbook? I have some code which should only work if a
worksheet (with a known name) exists in the user's
workbook.

Thanks.

Chip Pearson

Worksheet Exists...
 
James,

Try the following function:

Function WorksheetExists(WSName As String, _
Optional WB As Workbook) As Boolean
On Error Resume Next
WorksheetExists = CBool(Len(IIf(WB Is Nothing, _
ActiveWorkbook, WB).Worksheets(WSName).Name))
End Function


You can then call this in code with something like

If WorksheetExists("Sheet1",ThisWorkbook) = True Then
' whatever
Else
' whatever else
End If


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
www.cpearson.com


"James Weaver" wrote in message
...
How do you find out if a worksheet exists or not within a
workbook? I have some code which should only work if a
worksheet (with a known name) exists in the user's
workbook.

Thanks.




Bob Phillips[_5_]

Worksheet Exists...
 
James,

Here's one way

Dim oWS As Worksheet

On Error Resume Next
Set oWS = Activeworkbook.Worksheets("Sheet1")
On Error GoTo 0
If oWS Is Nothing Then
MsgBox "Worksheet does not exist"
End If


--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)

"James Weaver" wrote in message
...
How do you find out if a worksheet exists or not within a
workbook? I have some code which should only work if a
worksheet (with a known name) exists in the user's
workbook.

Thanks.




James Weaver

Worksheet Exists...
 
Thanks - very effective!
-----Original Message-----
James,

Here's one way

Dim oWS As Worksheet

On Error Resume Next
Set oWS = Activeworkbook.Worksheets("Sheet1")
On Error GoTo 0
If oWS Is Nothing Then
MsgBox "Worksheet does not exist"
End If


--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)

"James Weaver" wrote in message
...
How do you find out if a worksheet exists or not within

a
workbook? I have some code which should only work if a
worksheet (with a known name) exists in the user's
workbook.

Thanks.



.



All times are GMT +1. The time now is 05:34 AM.

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