ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   How do I Test for the existence of a Worksheet from inside a Macro (https://www.excelbanter.com/excel-programming/385759-how-do-i-test-existence-worksheet-inside-macro.html)

JB

How do I Test for the existence of a Worksheet from inside a Macro
 
I'm trying to run a macro, but sometimes theres a worksheet in place and
sometimes there isn't. If its not there I need to add it, but if it there
and I try to add it i get an error. Anyone know how to do an if statement
around something like this.

Thanks,

Gary''s Student

How do I Test for the existence of a Worksheet from inside a Macro
 
Sub nosheet()
isthere = False
For Each w In Worksheets
If w.Name = "Sheetxx" Then
isthere = True
End If
Next

If isthere Then
MsgBox ("it's already there")
Else
MsgBox ("It's not there")
End If
End Sub

--
Gary''s Student
gsnu200711


"jb" wrote:

I'm trying to run a macro, but sometimes theres a worksheet in place and
sometimes there isn't. If its not there I need to add it, but if it there
and I try to add it i get an error. Anyone know how to do an if statement
around something like this.

Thanks,


Dave Peterson

How do I Test for the existence of a Worksheet from inside a Macro
 
I stole this from Chip Pearson:

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

jb wrote:

I'm trying to run a macro, but sometimes theres a worksheet in place and
sometimes there isn't. If its not there I need to add it, but if it there
and I try to add it i get an error. Anyone know how to do an if statement
around something like this.

Thanks,


--

Dave Peterson


All times are GMT +1. The time now is 03:02 PM.

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