Subscript out of range

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TheServant
    Recognized Expert Top Contributor
    • Feb 2008
    • 1168

    Subscript out of range

    Hi guys,
    I am trying to test if a worksheet exists (VBA - Excel) but I cannot seem to catch the error. It always will give a runtime error and I need a sure way to test if the worksheet exists so I can exit the Sub and display a helpful msg. Here is the code,a nd would appreciate some help:

    Code:
        If IsError(Application.Workbooks(RODocList.Value).Sheets("1")) Then
            Exit Sub
            MsgBox ("Workbook not found. Please make sure you have selected the correct workbook")
        End If
  • ubentook
    New Member
    • Dec 2007
    • 58

    #2
    Here is one way.
    It assumes the sheet is actually named "1" (without the quote marks)
    To reference the first sheet in the workbook, you would use: Workbooks("RODo cList").Sheets( 1)
    '--
    Code:
    Sub React()
    Dim wbSheet As Worksheet
    On Error Resume Next
    Set wbSheet = Workbooks("RODocList").Sheets("1")
    If Err.Number <> 0 Then
       MsgBox ("Workbook not found. Please make sure you have selected the correct workbook")
       Exit Sub
    End If
    On Error GoTo HandleError
    
    'more code
    'note: you can use wbSheet in your code.
    
    Exit Sub
    HandleError:
       MsgBox "There is no hope."
    End Sub

    Comment

    • TheServant
      Recognized Expert Top Contributor
      • Feb 2008
      • 1168

      #3
      Great! Thanks for you help, that's exactly what I wanted.

      Comment

      Working...