+ Reply to Thread
Results 1 to 4 of 4

If Worksheet exists...Then run code

  1. #1
    PCLIVE
    Guest

    If Worksheet exists...Then run code

    I'm looking for some code that will allow me to search for a specific
    worksheet.

    If it doesn't exist, then run some code.
    The code below obviously doesn't work. How can I rewrite this?


    If Sheets(CurrentModel).Activate = Error Then
    'run code'

    Else
    Sheets(CurrentModel).Activate
    End If


    Thanks,
    Paul



  2. #2
    Forum Contributor
    Join Date
    06-13-2004
    Posts
    120
    Put this where you want the code. This will loop through all the sheet names looking for the name you specify.

    For each WS in worksheets
    if WS.name = "sheetname" 'sheet to be found
    'code to be run
    else:
    'alternate code to be run
    end if
    next WS

  3. #3
    GS
    Guest

    RE: If Worksheet exists...Then run code

    try this:

    Function bSheetExists(wksName As String) As Boolean
    ' Checks if a specified worksheet exists.
    '
    ' Arguments: wksName The name of the worksheet
    '
    ' Returns: TRUE if the sheet exists

    Dim x As Worksheet
    On Error Resume Next
    Set x = ActiveWorkbook.Sheets(wksName)
    bSheetExists = (Err = 0)

    End Function

    To use:
    If bSheetExists("NameOfSheet") Then...
    -OR-
    If Not bSheetExists("NameOfSheet") Then...

    Hope this helps!
    GS

  4. #4
    PCLIVE
    Guest

    Re: If Worksheet exists...Then run code

    Sorry dok112,

    I guess I worded this slightly incorrect. What I really need is to run code
    if the sheet does NOT exist. I'm not sure this is possible with this type
    of code.

    I'll keep trying.
    Thanks.

    "dok112" <dok112.23e3qr_1140207009.799@excelforum-nospam.com> wrote in
    message news:dok112.23e3qr_1140207009.799@excelforum-nospam.com...
    >
    > Put this where you want the code. This will loop through all the sheet
    > names looking for the name you specify.
    >
    > For each WS in worksheets
    > if WS.name = "sheetname" 'sheet to be found
    > 'code to be run
    > else:
    > 'alternate code to be run
    > end if
    > next WS
    >
    >
    > --
    > dok112
    > ------------------------------------------------------------------------
    > dok112's Profile:
    > http://www.excelforum.com/member.php...o&userid=10581
    > View this thread: http://www.excelforum.com/showthread...hreadid=513809
    >




+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1