Forum Discussion
jukhamil
Sep 30, 2021Brass Contributor
Print files in directory with Dir()
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
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