Solved

Counting Files in a Directory...

Posted on 2004-08-18
4
302 Views
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()

Loop
    Exit Function
badDirectory:
    'come here if directory can not be accessed
    MsgBox "The directory you specified does not exist or " & _
            "can not be accessed.  Activity halted."
    End
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.

Thanks,
Ron
0
Comment
Question by:ronaldj
  • 2
4 Comments
 
LVL 15

Accepted Solution

by:
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
  Else
    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
  Else
    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)
  Next  

  ' 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
  Next

  ' Return the file count
  enumerate_Folders = int_File_Count

End Function

Regards

Scott
0
 

Author Comment

by:ronaldj
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
.NewSearch

'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,
Ron
0
 
LVL 15

Expert Comment

by:Colosseo
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 :)

Scott
0

Featured Post

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles from a Windows Server 2008 domain controller to a Windows Server 2012 domain controlle…
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 …

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now