Error Checking in Excel
Thanks Thanks:  0
Likes Likes:  0
Results 1 to 6 of 6

Thread: worksheet if...then

  1. #1
    Board Regular
    Join Date
    Apr 2002
    Location
    Alberta, Canada
    Posts
    50
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    I need to create a macro that will search my workbook for sheet "Data" and if there is no sheet called "Data" then create a new sheet and name it Data. If Data is present then the macro does nothing. Any suggestions?

  2. #2
    MrExcel MVP Jay Petrulis's Avatar
    Join Date
    Mar 2002
    Location
    Chicago, IL USA
    Posts
    2,040
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    The routine Add_Data_Sheet() calls a private function SheetExists, so both are required.

    Code:
    Sub Add_Data_Sheet()
    
    If SheetExists("Data") = False Then
        Worksheets.Add After:=Sheets(ThisWorkbook.Worksheets.Count)
        ActiveSheet.Name = "Data"
    End If
    
    End Sub
    
    Private Function SheetExists(sheetname) As Boolean
    Dim abc As Object
    On Error Resume Next
    Set abc = ActiveWorkbook.Sheets(sheetname)
    If Err = 0 Then SheetExists = True _
    Else SheetExists = False
    End Function

  3. #3
    Board Regular
    Join Date
    Apr 2002
    Location
    Alberta, Canada
    Posts
    50
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    i get a compile error: else without if with

    Else: SheetExists = False


  4. #4
    MrExcel MVP Jay Petrulis's Avatar
    Join Date
    Mar 2002
    Location
    Chicago, IL USA
    Posts
    2,040
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    I cannot replicate your error.

    Try to rewrite it as:

    Code:
    If Err = 0 Then
        SheetExists = True
    Else
        SheetExists = False
    End If

  5. #5
    MrExcel MVP Jay Petrulis's Avatar
    Join Date
    Mar 2002
    Location
    Chicago, IL USA
    Posts
    2,040
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    I *can* replicate it.

    You need to insert an underscore at the end of the first line, as this is actually only one line.

    If Err = 0 Then SheetExists = True Else SheetExists = False

    [ This Message was edited by: Jay Petrulis on 2002-05-03 14:29 ]

  6. #6
    Board Regular
    Join Date
    Apr 2002
    Location
    Alberta, Canada
    Posts
    50
    Post Thanks / Like
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Default

    both those worked. thanks

Some videos you may like

User Tag List

Like this thread? Share it with others

Like this thread? Share it with others

Posting Permissions

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