1

I'm having issues with the Dir() function in Excel VBA. When I run the below code, the code repeats as expected until there are no more files that match my condition. Once the Dir() call should run out of files to return I get a Run-time error '1004': Application-defined or object-defined error. I've tried all the other answers I could find that even remotely seemed like they applied to my situation.

Dim dataIter As Range
Dim outputIter As Range
Dim fileName As String
Dim wkbk As Workbook

fileName = Dir(path & "\" & "*.xlsm")
Do While Len(fileName) > 0
    Set wkbk = Workbooks.Open(path & "\" & fileName)
    Set dataIter = wkbk.Sheets(1).Range("A1")
    Do While dataIter.Address <> wkbk.Sheets(1).Range("TITLE").Address
        If dataIter.Value <> "" Then
            'Extract the data I need
            Set outputIter = outputIter.Offset(1)
        End If
        Set dataIter = dataIter.Offset(1)
    Loop
    wkbk.Close False
    fileName = Dir() 'Fails here
Loop

Valid assumptions:

  1. All needed sheets are the first in each workbook
  2. All sheets have a properly placed "TITLE" named range

What could be causing this and what can I do to fix this?

1 Answer 1

1

Here's a quick fix using some error handling, since your code runs as expected until the end.

Sub test()

    Dim dataIter As Range
    Dim outputIter As Range
    Dim fileName As String
    Dim wkbk As Workbook

    fileName = Dir(path & "\" & "*.xlsm")
    Do While Len(fileName) > 0
        Set wkbk = Workbooks.Open(path & "\" & fileName)
        Set dataIter = wkbk.Sheets(1).Range("A1")
        Do While dataIter.Address <> wkbk.Sheets(1).Range("TITLE").Address
            If dataIter.Value <> "" Then
                'Extract the data I need
                Set outputIter = outputIter.Offset(1)
            End If
            Set dataIter = dataIter.Offset(1)
        Loop
        wkbk.Close False
        On Error GoTo ErrHandler
        fileName = Dir() 'Fails here
        On Error GoTo 0
    Loop

    ' Any Remaining code

    Exit Sub
ErrHandler:
    If Err.Number = 1004 Then
        fileName = vbNullString
        Err.Clear
        Resume Next
    End If

End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

This worked! Thank you. Any idea why Dir is throwing this error?
Because at the end there is no Dir(). You already went through all of them therefore Dir() doesn’t exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.