Counting Files in a Directory...

Situation: I have 2 folders in C:/... f1 called ScannedClientDocs (all files of interest are scanned straight in. i.e., NO subfolders) and f2 named ClientDocs which is further broken down into sub-folders where eventually the .jpg resides. I want to compare the # of .jpg images in each. I know the following will correctly give me a count for f1:

Sub Count_Files_In_A_Directory()
  Dim I
  'get the number of files by calling a user function
  I = CountFiles("C:\ScannedClientDocs") 'Scanned
  'display the results in a message box
  MsgBox "There are " & I & _
            " jpg files in the directory you specified"
End Sub

Function CountFiles(tgtDir As String) As Integer
    Dim fName As String
    'Retrieve the first entry, handle error if directory not found

On Error GoTo badDirectory
    fName = Dir(tgtDir & "\*.jpg")
    On Error GoTo 0
    'loop through all files in the directory and increment the function's value
    Do While fName <> ""
        ' Ignore the current directory and
        ' the encompassing directory.
        If fName <> "." And fName <> ".." Then
            CountFiles = CountFiles + 1
        End If
        ' Get next entry.
        fName = Dir()

    Exit Function
    'come here if directory can not be accessed
    MsgBox "The directory you specified does not exist or " & _
            "can not be accessed.  Activity halted."
End Function

How do I get this routine (or reasonable facsimile thereof!) to get into the "bowels" (i.e., sub folder of sub folder) of ClientDocs so as to count the .jpg files?

I believe this can be done since if you right click the ClientDocs folder in C it tells me the # of files AND folders present.

Who is Participating?
Hi Ron

I'm not familiar with the way you are enumerating the directory but i have what I hope is a reasonable facsimile.

assuming you are using vb the following should work no problem.

The code works by getting the folders in a sub directory and recursively(spelling) calling the enumerate_Folders function to drill down in to all subfolders counting jpgs as it goes.

Hope thats what you need or at least points you in the right direction for your own code.

Dim oFSO
' Run the program passing the two folders to compare
compare_folders "c:\temp", "c:\tempnested"

sub compare_folders(str_Folder_1, str_Folder_2)

  ' The filesystemobject
  Set oFSO = CreateObject("Scripting.FileSystemObject")

  ' If the file counts for the two folders match
  If count_Files(str_Folder_1) = count_Files(str_Folder_2) Then
    Msgbox "File counts match"
  ' If the file counts do not match
    Msgbox "File counts do not match"
  End If

  ' Tidy up
  Set oFSO = Nothing

End Sub

' Returns the count of the number of files in this folder and its subfolders
Function count_Files(str_Folder)

  ' If this folder exists then count the files
  If oFso.FolderExists(str_Folder) Then
    ' Set the file counter to 0
    int_File_Count = 0
    ' Enumerate all the files
    count_Files = enumerate_Folders(str_Folder, int_File_Count)
  ' If the folder does not exist return 0
    count_Files = 0
  End If
End Function

' Enumerates files in the current folder and its sub folders
Function enumerate_Folders(str_Folder, int_File_Count)

  ' Create an object fot this folder
  Set oFolder = oFSO.GetFolder(str_Folder)

  ' For each sub folder
  For Each oSubFolder In oFolder.SubFolders
    ' Enumerates the sub folders files and its sub folders
    int_File_Count = enumerate_Folders(oSubFolder.Path, int_File_Count)

  ' For each file in this folder
  For Each oFile In oFolder.Files
    ' If the file is a jpg

   If LCase(oFso.GetExtensionName(oFile)) = "jpg" Then
      ' Increment the counter by 1
      int_File_Count = int_File_Count + 1
    End If

  ' Return the file count
  enumerate_Folders = int_File_Count

End Function


ronaldjAuthor Commented:
Hey Scott,

Thanks for the response. Yeah, the directory structure is kinda wierd but not my idea. Here's what happens: Client scans documents required by regulator into one massive folder called ScannedClientDocs(pretty original, huh?) Example: MrXYZdd.jpg.

I wrote a vba routine that creates a general folder called ClientDocs; under the general folder a folder named MrXYZ is then created. Sub to this is a folder called DueDilligence (grabs dd from lookup function and uses long name, DueDilligence to name folder). In this folder the document MrXYZdd.jpg is then copied/stored. So now, from a UserForm, the client selects an account, program auto selects all docs associated with same, puts them into a temp folder which is then made accessible to MS Picture and Fax Viewer. Kinda neat. So much for the bacxkground...

Your response triggered an idea so here's what I tried...seems to do the trick:

Sub FindClientDocsJPGFiles()
Dim FS As Office.FileSearch
Dim vaFileNattle As Variant
Dim stMessage As String
Dim i As Long, iCount As Long

Set FS = Application.FileSearch

With FS
'Clear old search criteria

'Directory to search
.LookIn = "C:\ClientDocs"

'Include sub folders in search
.SearchSubFolders = True

'Look for .jpg files
.filename = "*.jpg"
'.FileType = msoFileTypeAllFiles

'Doesn 't matter when last modified
.LastModified = msoLastModifiedAnyTime

'Carry out search and capture number of files found
iCount = .Execute

stMessage = Format(iCount, "0 ""Files Found""")
'List the files in the FoundFiles collection
For Each vaFileName In .FoundFiles
stMessage = stMessage '& vbCr & vaFileName
Next vaFileName

MsgBox stMessage

End With

End Sub

Obviously the msg lines are only there temp so I could see the result. Whatcha think?

Thanks again,
Hey Ron

Yeah my code was only an example of how I would do it using the filesystemobject.

Like you say and from what I understand of your code it should work fine. The .SearchSubFolders = True is perfect for what you need as this sends the code into the subfolders like my code so it looks like you have it sorted :)

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.