Dir Skipping Files

L

LarryP

Why does the following code only list three of the six .xls files in my c:\
directory?

Public Sub ListOfFiles()
Dim x As Integer, strFName As String
Debug.Print Dir("c:\*.xls")
For x = 1 To 1000
strFName = Dir
If strFName = "" Then
Exit For
Else
Debug.Print Dir()
End If
Next x

End Sub
 
D

Douglas J. Steele

You're calling Dir twice inside the loop. Try

Public Sub ListOfFiles()
Dim x As Integer, strFName As String
Debug.Print Dir("c:\*.xls")
For x = 1 To 1000
strFName = Dir
If strFName = "" Then
Exit For
Else
Debug.Print strFName
End If
Next x

End Sub

Better, though, would be

Public Sub ListOfFiles()
Dim strFName As String

strFName = Dir("c:\*.xls")
Do While Len(strFName) = 0
Debug.Print strFName
strFName = Dir()
Loop

End Sub
 
L

LarryP

Thanks as always, Doug. Love your nice tight code, but seems like the Do
While would result in nothing ever getting printed if any file is found.
Shouldn't it be Do Until?

By the way, related: this is great for as long as one is searching for a
particular filename pattern in a particular folder, but can you suggest a way
to make it iterate through subfolders as well? I'm after the same
functionality I enjoyed with Application.Filesearch, where one feeds it the
filename pattern and the starting point for the search as separate strings.
I'm thinking one needs a construct along the lines of
"c:\startingpointfolder" & "\*\" & "filenamepattern.*" but I can't quite
connect the dots.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top