Counting Files in a Directory...

Posted on 2004-08-18
Last Modified: 2010-04-17
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.

Question by:ronaldj
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
LVL 15

Accepted Solution

Colosseo earned 300 total points
ID: 11834664
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



Author Comment

ID: 11835488
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,
LVL 15

Expert Comment

ID: 11835862
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 :)


Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
Recently, Microsoft released a best-practice guide for securing Active Directory. It's a whopping 300+ pages long. Those of us tasked with securing our company’s databases and systems would, ideally, have time to devote to learning the ins and outs…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

687 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question