Help with code that checks if a sheet exists

  • Thread starter Thread starter wachen
  • Start date Start date
W

wachen

I use the following code to check if a worksheet exists. It works OK if the
worksheet does exist, However, if the worksheet does not exist, then
the "Set" statement gives a "Subscript out of range" error.

Can someone please help? Thanks.

Sub checkit ()
Dim NewTabName As String, WkSht As Worksheet
NewTabName = "1-23-04"

Set WkSht = Workbooks(CurBookName).Worksheets(NewTabName)
If Not WkSht Is Nothing Then
MsgBox "The worksheet exists"
Else
Workbooks(CurBookName).Activate
Workbooks(CurBookName).Sheets.Add.Name = NewTabName
End If
End Sub
 
Wache

One way is to add the lin
On Error Resume Nex
before the Set command

Also, you should initialise the CurBookName variable

Ton

----- wachen wrote: ----

I use the following code to check if a worksheet exists. It works OK if th
worksheet does exist, However, if the worksheet does not exist, the
the "Set" statement gives a "Subscript out of range" error

Can someone please help? Thanks

Sub checkit (
Dim NewTabName As String, WkSht As Workshee
NewTabName = "1-23-04

Set WkSht = Workbooks(CurBookName).Worksheets(NewTabName
If Not WkSht Is Nothing The
MsgBox "The worksheet exists
Els
Workbooks(CurBookName).Activat
Workbooks(CurBookName).Sheets.Add.Name = NewTabNam
End I
End Su
 
Wachen, make the following changes:

On error resume next
Set WkSht = Workbooks(CurBookName).Worksheets(NewTabName)
On error goto 0

The first on error statement allows the following line to run with an error.
The second turns off this feature.

Bob Flanagan
Macro Systems
http://www.add-ins.com
Productivity add-ins and downloadable books on VB macros for Excel
 

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

Similar Threads

Autofilter (on/off) 1
variable not set error? 4
Inconsistent macro behavior 2
exclusion list in code 2
End if w/o if? 22
Which is unsupported? 4
Find and Copy 2
Protect/unprotect worksheets 2

Back
Top