Print files in directory with Dir()

%3CLINGO-SUB%20id%3D%22lingo-sub-2798352%22%20slang%3D%22en-US%22%3EPrint%20files%20in%20directory%20with%20Dir()%3C%2FLINGO-SUB%3E%3CLINGO-BODY%20id%3D%22lingo-body-2798352%22%20slang%3D%22en-US%22%3E%3CP%3EI%20am%20trying%20to%20print%20all%20the%20files%20in%20a%20directory%20with%20the%20Dir()%20function%20but%20it%20isn't%20working%20as%20expected.%20It%20usually%20either%20returns%20a%20blank%20string%20or%20just%20the%20name%20of%20the%20directory%20I%20passed%20in%20the%20path%2C%20rather%20than%20the%20directories%20inside%20that%20directory.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EFor%20example%3A%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EDir(%22C%3A%5CUsers%5Cjuhamilton%5CDesktop%22%2C%20vbNormal)%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3Ereturns%20nothing%2C%20and%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EDir(%22C%3A%5CUsers%5Cjuhamilton%5CDesktop%22%2C%20vbDirectory)%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3Ereturns%20%22Desktop%22.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EWhy%20is%20this%20and%20how%20could%20I%20print%20out%20a%20list%20of%20all%20files%20in%20a%20directory%3F%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3CP%3EThank%20you.%3C%2FP%3E%3CP%3E%26nbsp%3B%3C%2FP%3E%3C%2FLINGO-BODY%3E%3CLINGO-LABS%20id%3D%22lingo-labs-2798352%22%20slang%3D%22en-US%22%3E%3CLINGO-LABEL%3EMacros%20and%20VBA%3C%2FLINGO-LABEL%3E%3C%2FLINGO-LABS%3E
Contributor

I am trying to print all the files in a directory with the Dir() function but it isn't working as expected. It usually either returns a blank string or just the name of the directory I passed in the path, rather than the directories inside that directory.

 

For example:

 

Dir("C:\Users\juhamilton\Desktop", vbNormal)

 

returns nothing, and

 

Dir("C:\Users\juhamilton\Desktop", vbDirectory)

 

returns "Desktop".

 

Why is this and how could I print out a list of all files in a directory?

 

Thank you.

 

1 Reply

@jukhamil 

For example:

Sub Example()
    Call ListFiles("C:\Users\juhamilton\Desktop")
End Sub

Sub ListFiles(ByVal sPath As String)
    Dim sFile As String
    If Right(sPath, 1) <> "\" Then
        sPath = sPath & "\"
    End If
    sFile = Dir(sPath & "*.*")
    Do While sFile <> ""
        Debug.Print sFile
        sFile = Dir
    Loop
End Sub