Share via

macro skips workbook if specific tab doesn't exist

Anonymous
2012-04-20T00:07:53+00:00

I have created a macro that loops through all files in a subdirectory and pulls info I need.  I would now like it to skip the workbook if it doesn't include a tab with a specific name.  For example if tab "Risks Follow Up" doesn't exist close the workbook and go the next one in the subdirectory.  Thank you!

Below is the current code.

Workbooks.Open "H:\Daniel\RiskAssessment2012_MASTERFILE_results.xlsm"

    strFolder = "H:\Daniel\Files"

    strSubFolder = Dir(strFolder & "*", vbDirectory)

    Do While Not strSubFolder = ""

        Select Case strSubFolder

            Case ".", ".."

                ' Current folder or parent folder - ignore

            Case Else

                ' Add to collection

                colSubFolders.Add Item:=strSubFolder, Key:=strSubFolder

        End Select

        ' On to the next one

        strSubFolder = Dir

    Loop

    ' Loop through the collection

    For Each varItem In colSubFolders

        ' Loop through Excel workbooks in subfolder

        strFile = Dir(strFolder & varItem & "\*.xls*")

        Do While strFile <> ""

            ' Open workbook

            Set wbk = Workbooks.Open(FileName:=strFolder & _

                varItem & "" & strFile, AddToMRU:=False)

Code to pull info I need.

   strFile = Dir

        Loop

    Next varItem

    'End 'for each looking at sheet name

    MsgBox NSheetCount & " worksheets copied from directory " & strFolder

End Sub

Microsoft 365 and Office | Excel | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2012-04-20T03:41:43+00:00

Try putting this in right after you do the **Set wbk = Workbooks.Open....**statement:

  Dim testWS As Worksheet

  On Error Resume Next

  Set testWS = wbk.worksheets("Risks Follow Up")

  If Err = 0 Then

    On Error GoTo 0 ' reset error trapping

    'the sheet does exist, do your stuff

  Else

    'the sheet did not exist

    Err.Clear

    On Error GoTo 0

  End If

Was this answer helpful?

0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2014-08-24T21:31:11+00:00

    Thanks for letting us know - I like giving gifts that keep on giving in a good way!

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2014-08-14T08:02:41+00:00

    Awesome!!

    You help me solve my problem too~

    Thank you very much JLLatham :D

    Was this answer helpful?

    0 comments No comments