Skip to content

Instantly share code, notes, and snippets.

@mrowles
Created December 11, 2012 22:52
Show Gist options
  • Save mrowles/4263087 to your computer and use it in GitHub Desktop.
Save mrowles/4263087 to your computer and use it in GitHub Desktop.
Microsoft Excel: Finds all files in a specified directory with an optional specified criteria (extension, name)
Sub ListFilesInDirectory()
Dim fsFile, sFilename, sPath As String
Dim i As Integer
i = 2
'Set file attributes
sPath = "C:\"
sFilename = "*.pdf"
'Checks if directory empty
If Dir(sPath, vbDirectory) <> "" Then
fsFile = Dir(sPath & sFilename)
'Iterates through each file in the directory
Do While fsFile <> ""
Cells(i, 1).Value = fsFile
i = i + 1
fsFile = Dir
Loop
'Whilst directory wasn't empty, this determines if files matching criteria were found or not
If (i = 2) Then
MsgBox "No files like " & sFilename & " found"
End If
Else
'No files found, display message
MsgBox "No files Found"
End If
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment