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:
- All needed sheets are the first in each workbook
- All sheets have a properly placed "TITLE" named range
What could be causing this and what can I do to fix this?