Consulting

Results 1 to 11 of 11

Thread: Help with Error Handling

  1. #1
    VBAX Contributor
    Joined
    Mar 2009
    Location
    Indiana
    Posts
    113
    Location

    Question Help with Error Handling

    Hello,

    I am trying to figure out how to use error handling to skip and iteration. Here is my code:

    Sub AddSheets(Host, Data1, Data2)
    Set NewSht = Sheets.Add(after:=Sheets(Sheets.count), Type:=xlWorksheet)
    'I know this is really bad practice for error handling and this is where I need help
    On Error Resume Next
    With NewSht
      .Name = Host
      .Range("A1").Value = Data1
      .Range("A2").Value = Data2
    End With
    End Sub
    I am trying to prevent a new sheet being created with the same name as another sheet. Without the "On Error Resume Next" line, I get the following error:

    Run-time error '1004':
    Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by Visual Basic

    I am using Microsoft Excel 2010. Any help would be greatly appreciated!

  2. #2
    VBAX Expert
    Joined
    Oct 2012
    Posts
    726
    Location
    Sub AddSheets(Host, Data1, Data2)
        On Error Resume Next
        With Sheets.Add(after:=Sheets(Sheets.Count), Type:=xlWorksheet)
            If Err.Number Then
                'couldn't create sheet
            Else
                .Name = Host
                If Err.Number Then
                    'error renaming
                    Application.DisplayAlerts = 0
                    .Delete
                    Application.DisplayAlerts = 1
                else
                    .Range("A1").Value = Data1 
                    .Range("A2").Value = Data2
                    If Err.Number Then
                        '... some error
                    end if
                end if
            end if
        End With 
    End Sub

  3. #3
    VBAX Guru Kenneth Hobs's Avatar
    Joined
    Nov 2005
    Location
    Tecumseh, OK
    Posts
    4,956
    Location
    You might check if the worksheet name exists before trying to add it.
    Function Test_WorkSheetExists()  
      MsgBox "WorksheetExists? " & WorkSheetExists("Sheet1"), _
        vbInformation, "ActiveWorkbook.ActiveSheet"
    End Function
    
    
     'WorkSheetExists in a workbook:
    Function WorkSheetExists(sWorkSheet As String, Optional sWorkbook As String = "") As Boolean
        Dim ws As Worksheet, wb As Workbook
        On Error GoTo notExists
        If sWorkbook = "" Then
          Set wb = ActiveWorkbook
          Else
          Set wb = Workbooks(sWorkbook)
        End If
        Set ws = wb.Worksheets(sWorkSheet)
        WorkSheetExists = True
        Exit Function
    notExists:
        WorkSheetExists = False
    End Function

  4. #4
    VBAX Contributor
    Joined
    Mar 2009
    Location
    Indiana
    Posts
    113
    Location
    That seems to work great, but how would I get it to prompt when it is skipping a duplicate sheet? I tried adding in a MsgBox, but it didn't prompt.

    On Error Resume Next
      With Sheets.Add(after:=Sheets(Sheets.count), Type:=xlWorksheet)
        If Err.Number Then
          MsgBox "The worksheet '" & Host & "' already exists and will be skipped."
        Else
            .Name = Host
            If Err.Number Then
                'error renaming
                Application.DisplayAlerts = 0
                .Delete
                Application.DisplayAlerts = 1

  5. #5
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    The Error doesn't occur when you add the sheet, but when you rename it. You need to test Err.Number after that but Kenneth's method is preferable IMO.
    Be as you wish to seem

  6. #6
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    If Err.Number <> 0 Then 
            MsgBox "The worksheet '" & Host & "' already exists and will be skipped." 
        Else
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

  7. #7
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,726
    Location
    Or maybe ...


    Option Explicit
    
    Sub AddSheets(Host As String, Data1 As Variant, Data2 As Variant)
        Dim wsExisting As Worksheet
        
        Set wsExisting = Nothing
        On Error Resume Next
        Set wsExisting = Worksheets(Host)
        On Error GoTo 0
        
        If Not wsExisting Is Nothing Then GoTo ExistsAlready
        
        'for some other reason
        On Error GoTo CannotCreate
        Sheets.Add after:=Sheets(Sheets.Count), Type:=xlWorksheet
        
        On Error GoTo CannotRename
        Sheets.Add after:=Sheets(Sheets.Count), Type:=xlWorksheet
            
        On Error GoTo SomeOtherError
        ActiveSheet.Range("A1").Value = Data1
        ActiveSheet.Range("A2").Value = Data2
        Exit Sub
    ExistsAlready:
        MsgBox Host & " exists already"
        Exit Sub
    
    SomeOtherError:
        MsgBox "ERROR!!! " & Err.Description & " (" & Err.Number & ")"
        Exit Sub
    
    CannotRename:
        MsgBox "Cannot rename " & ActiveSheet.Name & " to " & Host
        Exit Sub
    
    CannotCreate:
        MsgBox "Cannot create " & Host
        Exit Sub
    End Sub
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

  8. #8
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,720
    Location
    @Paul
    I think you mistyped the line to rename the sheet.
    Be as you wish to seem

  9. #9
    VBAX Expert
    Joined
    Oct 2012
    Posts
    726
    Location
    This got a bit ott so I gave up on it, but it provided different options for dealing with the name error, so I'll post it anyway.

    Public Enum SheetExistsOption
        overwrite
        useexisting
        cancelupdate
        changename_auto
        changename_prompt
    End Enum
    
    Sub AddSheet()
    On Error Resume Next
        Dim newS As Worksheet
        Set newS = NewSheet(NewWS_Name, ActiveWorkbook, SheetExistsOption.changename_prompt)
        
        If newS Is Nothing Then
            MsgBox "There was an error creating the new sheet :("
        Else
            With newS
                'hard coded ranges!
                AddData .Range("A1"), data1
                AddData .Range("A2"), data2
                
                'display msg if this 'special' one errors
                If Not AddData(.Range("A3"), data3) Then _
                    MsgBox "Error adding data" & Err.Description, _
                        vbExclamation, "Error " & Err.Number
            End With
        End If
    End Sub
    
    Public Function NewSheet(ShtName As String, wb As Workbook, seo As SheetExistsOption) As Worksheet
    On Error Resume Next
        If Not NameIsUnique(ShtName, wb) Then
            Select Case seo
            Case SheetExistsOption.cancelupdate
                Exit Function
            Case SheetExistsOption.changename_prompt
                Dim rv As String
                Do
                    ShtName = Trim(InputBox("Sheet name:", "Enter new sheet name", ShtName))
                    If ShtName = "" Then Exit Function
                Loop Until NameIsUnique(ShtName, wb)
            Case SheetExistsOption.changename_auto
                Dim i As Integer, tmps As String
                Do
                    i = i + 1
                    tmps = ShtName & "_" & i
                    If NameIsUnique(tmps, wb) Then
                        ShtName = tmps
                        Exit Do
                    End If
                Loop
            Case SheetExistsOption.overwrite
                Set NewSheet = wb.Sheets(ShtName)
                NewSheet.Cells.Delete
                Exit Function
            Case SheetExistsOption.useexisting
                Set NewSheet = wb.Sheets(ShtName)
                Exit Function
            End Select
        End If
        
        Set NewSheet = CreateNamedSheet(ShtName, wb)
    End Function
    
    Public Function CreateNamedSheet(ShtName As String, wb As Workbook) As Worksheet
    On Error Resume Next
        Set CreateNamedSheet = wb.Sheets.Add(after:=Sheets(Sheets.Count), Type:=xlWorksheet)
            If Err.Number = 0 Then
                With CreateNamedSheet
                    .Name = ShtName
                    If Err.Number Then
                        CreateNamedSheet = Nothing
                        Application.DisplayAlerts = 0
                        .Delete
                        Application.DisplayAlerts = 1
                    End If
                End With
            End If
    End Function
    
    Public Function NameIsUnique(ShtName As String, wb As Workbook) As Boolean
    On Error Resume Next
        Dim newS As Worksheet
        Set newS = wb.Worksheets(ShtName)
        NameIsUnique = newS Is Nothing
    End Function
    
    Private Function AddData(rng As Range, val As Variant) As Boolean
    On Error Resume Next
        rng = val
        If Err.Number Then
            Debug.Print "error setting", rng.Address, "to",
            Debug.Print val
            Debug.Print
        Else
            AddData = True
        End If
    End Function

  10. #10
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    Jonh,

    That could be an article or Blog entry.
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

  11. #11
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,726
    Location
    Quote Originally Posted by Aflatoon View Post
    @Paul
    I think you mistyped the line to rename the sheet.
    A. It was a test to see if anyone was reading?

    B. The kyebarerd was messed up?

    C. I was copy/pasting too much?

    D. Re-designing on the fly since I REALLY wasn't sure what the OP wanted for logic flow?



    And the answer is ....




    D




    (probably)
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

Posting Permissions

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