MrExcel Message Board

Go Back   MrExcel Message Board > Question Forums > Excel Questions

Excel Questions All Excel/VBA questions - formulas, macros, pivot tables, general help, etc. Please post to this forum in English only.

Reply
 
Thread Tools Display Modes
Old Mar 26th, 2002, 01:35 AM   #1
jrnyman
Board Regular
 
Join Date: Mar 2002
Location: Boston, MA
Posts: 105
Default

Does anyone know the code for checking if a worksheet exists. The worksheets name will be the String "NewSht" followed by either the letter "L" or "B". I'm trying to check if the sheet exists, and if it does, overwrite all its cells. If it doesn't, I need to create a new sheet with that name. Thanks for the help.
jrnyman is offline   Reply With Quote
Old Mar 26th, 2002, 01:43 AM   #2
Dave Hawley
Banned
 
Join Date: Feb 2002
Posts: 1,582
Default

Hi

If you are going to overwrite them anyway, Just use this:

Application.DisplayAlerts = False
On Error Resume Next
Sheets("NewShtL").Delete
Sheets("NewShtB").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Sheets.Add().Name = "NewSht"


But to check if sheet exists you would use

Dim wsSheet As Worksheet
On Error Resume Next
Set wsSheet = Sheets("NewShtL")
On Error GoTo 0
If Not wsSheet Is Nothing Then
MsgBox "I do exist"
Else
MsgBox "I do NOT exist"
End If


Dave Hawley is offline   Reply With Quote
Old Mar 26th, 2002, 02:07 AM   #3
Colo
MrExcel MVP
 
Colo's Avatar
 
Join Date: Mar 2002
Location: Kobe, Japan
Posts: 1,420
Default

Hi. The following code is using Loop.
Please try. Regards,

Sub Test()
Dim sh As Worksheet, flg As Boolean
For Each sh In Worksheets
If sh.Name Like "NewSht*" Then flg = True: Exit For
Next
If flg = True Then
MsgBox "Found!"
Else
Sheets.Add.Name = "NewSht"
End If
End Sub
Colo is offline   Reply With Quote
Old May 3rd, 2007, 04:22 PM   #4
chazz
Board Regular
 
Join Date: Jul 2006
Posts: 63
Default very clever.

setting the non-existent sheet as an object and then blowing through the errors is clever indeed.

also learned from the use of wildcard * in the second suggestion.
chazz is offline   Reply With Quote
Old Jun 16th, 2009, 04:20 PM   #5
Spencer Jobe
New Member
 
Join Date: Jun 2009
Posts: 4
Default Re: VBA to check if a worksheet exists

Public Function WorksheetExists(ByVal WorksheetName As String) As Boolean

On Error Resume Next
WorksheetExists = (Sheets(WorksheetName).Name <> "")
On Error GoTo 0

End Function

Last edited by Spencer Jobe; Jun 16th, 2009 at 04:25 PM.
Spencer Jobe is offline   Reply With Quote
Old Sep 19th, 2010, 11:48 AM   #6
High Plains Grifter
Board Regular
 
Join Date: Mar 2010
Location: Chichester, England
Posts: 98
Default Re: VBA to check if a worksheet exists

I am having problems implementing the code to check whether a sheet already exists in my own macro - for some reason, the following code always seems to think that the new sheet name already exists, and asks whether I would like to overwrite it, even when the sheet in question patently does not exist. Below is a section of the macro, containing the relevant code:
Code:
Sub NewSheets()
Dim agent As String
Dim lastone As String
Dim i As Integer
Dim max As Integer
Dim ws As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
max = InputBox("How Many Rows down the list do you wish to use?", "Enter a number to create that number of sheets")
For i = 1 To max
    'for the first of the new sheets, the previous sheet is called template, by definition
    If i = 1 Then
            lastone = "Template"
    'otherwise, the last previous sheet name will be one higher in the list than the current
    Else
            lastone = Worksheets("Lists").Range("A1").Offset(i - 1, 0).Value
    End If
        'get the agent name
        agent = Worksheets("Lists").Range("A1").Offset(i, 0).Value
        'check whether a sheet with that name already exists
        On Error Resume Next
        Set ws = Sheets(agent)
    'if none with that name, create a new sheet
    If ws Is Nothing Then
            ActiveWorkbook.Sheets("Template").Copy after:=ActiveWorkbook.Sheets(lastone)
            ActiveSheet.Name = agent
    'if the sheet already exists, ask whether the user wants to replace it
    Else
            overW = MsgBox("This sheet already exists - Overwrite?", vbYesNoCancel, agent)
        If overW = vbYes Then
                Sheets(agent).Delete
                ActiveWorkbook.Sheets("Template").Copy after:=ActiveWorkbook.Sheets(lastone)
                ActiveSheet.Name = agent
        ElseIf overW = vbNo Then
                GoTo Skip
        ElseIf overW = vbCancel Then
                Exit Sub
        End If
    End If
I cannot work out which part I have got wrong - can anyone help?

Thanks for looking at the post, and all replies are much appreciated!
High Plains Grifter is offline   Reply With Quote
Old Sep 19th, 2010, 04:21 PM   #7
xenou
MrExcel MVP
Moderator
 
Join Date: Mar 2007
Location: Cleveland OH
Posts: 10,937
Default Re: VBA to check if a worksheet exists

Possibly you have not reset ws as nothing:
Code:
        On Error Resume Next
        Set ws = Sheets(agent)
Try amending to:
Code:
        Set ws = Nothing
        On Error Resume Next
        Set ws = Sheets(agent)
Also not that error handling will be left "on" and may mask other problems now. So also preferable is:
Code:
        Set ws = Nothing
        On Error Resume Next
        Set ws = Sheets(agent)
        On Error GoTo 0
__________________
Using: Office 2007/XP SP3 (work), Excel 2010/XP SP3 (home)

One is not born into the world to do everything but to do something.
-- Henry David Thoreau
xenou is offline   Reply With Quote
Old Sep 19th, 2010, 04:44 PM   #8
High Plains Grifter
Board Regular
 
Join Date: Mar 2010
Location: Chichester, England
Posts: 98
Smile Thanks

Thanks - worked perfectly. I will look up what "on error goto 0" actually does and thus try to avoid that in the future.
High Plains Grifter is offline   Reply With Quote
Old Jan 31st, 2012, 07:45 PM   #9
Lil Smiles
New Member
 
Join Date: Jan 2012
Posts: 1
Default Re: VBA to check if a worksheet exists

Hey Guys,

I saw this thread and I wanted to show the code I came up with.

I don't like "On Error Resume Next" command so I made the following function:


Code:
Sub Testing()
    Dim SheetName1, SheetName2 As String
    Dim Result As Boolean
    Dim i As Long
    
    
    SheetName = Array("laskgfasdfalskg", "Config")
    
    For i = 0 To UBound(SheetName)
        Result = WorksheetExists(SheetName(i))
        If Result = False Then
            MsgBox "Sheet name " & SheetName(i) & " doesn't exist!"
        Else
            MsgBox "Sheet name " & SheetName(i) & " does exist!"
        End If
    Next i
    
    
End Sub



Public Function WorksheetExists(ByVal WorksheetName As String) As Boolean
    
    Dim Sht As Worksheet
        
    WorksheetExists = False
        
    For Each Sht In ActiveWorkbook.Worksheets
        If Sht.Name = WorksheetName Then worksheetexits = True
    Next Sht
    
End Function
Lil Smiles is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On

Forum Jump


All times are GMT -4. The time now is 03:15 PM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2012, vBulletin Solutions, Inc.
All contents Copyright 1998-2012 by MrExcel Consulting.
diabetic desserts recipes recipes Diabetic Soups Holiday Pizza Recipes Popcorn Recipes Recipes For Microwave Pasta Recipes Casserole Recipes Chili Recipes Curry Recipes Crockpot Recipes Apples Recipes Bread Recipes Vegetarian Recipes Vegetable recipes Desserts Recipes Appetizers Ethnic Recipes Meat Dishes Barbecue Recipes Sauces Recipes Marinade Recipes Low Fat Recipes Frugal Gourmet Kitchen Classics Recipes On The Grill Cook Books Seafood Recipes Cajun Recipes Breads Low Fat Low Fat Breads Bread Machine Recipes Yeast Breads Quick Breads Fat Free Vegetarian Salad Recipes Eggplant Recipes Radish Recipes Tomato Recipes Jalapeno Recipes Potato Recipes Lettuce Recipes Cabbage Recipes Beans Ambrosia Recipes Biscotti Recipes Desserts Low Fat Cookie Recipes Cheesecake Recipes Cake Recipes Pie Recipes Muffin Recipes Custard Recipes Best Appetizers Appetizers Low Fat Salsa Recipes Dip Recipes International Recipes Afghan Recipes Alaska Recipes French Recipes German Recipes Greek Recipes Italian Recipes Spanish Recipes Thai Recipes Korean Recipes Chinese Recipes Mexican Recipes Indian Recipes Beef Recipes Pork Pork & Ham Pork Butts Pork Chop Recipes Pork Ribs Rulled Pork Poultry Recipes Stews Recipes Ground Beef Barbecue Grill Barbecue Smoker All Purpose Sauce BBQ Sauce Barbecue Sauce Carolina BBQ Sauce Pickle Recipes Marinades Smoking Low Fat Appetizers & Dips Low Fat Breakfast Low Fat Cakes Low Fat Cheesecakes Low Fat Cookies Low Fat Desserts Low Fat Fish & Seafood Low Fat Meats Low Fat Pasta Low Fat Pies Low Fat Salads Low Fat Sandwiches Low Fat Sauces & Condiments Low Fat Sides Low Fat Soups Low Fat Vegetarian Baker's Dozen Taste of Home Recipe Book Bon Appetit Cookbook Blacktie Cookbook Buster Cook Book Cookbook USA Cook Book Cook Book Sara's Cookbook Sara's Cookbook Appetizers and Dips Poultry recipes Diabetic recipes Holiday recipes Miscellaneous recipes 110 recipes 1986 Usenet cookbook 2900 recipes Cyberrealm recipes Great sysops of world Specialty recipes Ceideburg recipes Cheese recipes Chili recipes Fruits recipes Garlic recipes Great chefs of NY Londontowne recipes Raisins recipes Recipes for kids US Food Vegetarian recipes Bread recipes Drinks Meat Dishes Brisket recipes Caribou recipes Chicken recipes Filet mignons recipes Pork recipes Swordfish recipes Turkey recipes Pasta recipes Uncategorized recipes Ethnic recipes Canada recipes English recipes Ethiopia recipes Germany recipes Greece recipes Mexican recipes Philippines recipes Welsh recipes Microwave recipes Soups recipes Vegetable recipes Asparagus recipes Barley recipes Brown rice recipes Lentil recipes Mushrooms recipes Salads recipes Wild rice Desserts recipes Cakes recipes Chocolate recipes Cookies recipes Ice cream recipes