VB and VBA Users Source Code: Counting all the files in a directory which match a specified pattern
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Counting all the files in a directory which match a specified pattern
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Wednesday, November 16, 2005
Hits:
3190
Category:
Files/Directories/IO
Article:
The code below counts all the files in a directory which match a specified pattern. 'Purpose : Counts all the files which match the specified pattern. 'Inputs : sFilePattern The full path and name or file pattern (can include either * or $) 'Outputs : Returns the count of the files or -1 if an error occurred 'Author : Andrew Baker 'Date : 07/09/2000 'Example : Debug.Print "Temp Files: " & FileCountMatching("C:\Temp\*.*") Function FileCountMatching(sFilePattern As String) As Long Dim sThisFile As String, sThisPath As String Dim sFileDelete As String Dim bErrored As Boolean On Error GoTo ErrFailed 'Count matching files sThisPath = PathFileToPath(sFilePattern) sThisFile = Dir(sFilePattern, vbNormal) Do While Len(sThisFile) If sThisFile <> "." And sThisFile <> ".." Then FileCountMatching = FileCountMatching + 1 End If sThisFile = Dir$ Loop On Error GoTo 0 Exit Function ErrFailed: Debug.Print "Failed to count files in " & sFilePattern & ". Error: " & Err.Description FileCountMatching = -1 End Function 'Purpose : Convert a file and path to a path e.g. "C:\Windows\Win.ini" becomes "C:\Windows\" 'Inputs : sFilePathName The path and file name to convert 'Outputs : Returns the file path 'Author : Andrew Baker 'Date : 25/03/2000 'Notes : Also works with URL's Function PathFileToPath(sFilePathName As String) As String Dim lThisChar As Long PathFileToPath = sFilePathName 'Default return value lThisChar = InStrRev(sFilePathName, "\") If lThisChar Then PathFileToPath = Left$(sFilePathName, lThisChar) Else 'Check remote paths lThisChar = InStrRev(sFilePathName, "/") If lThisChar Then PathFileToPath = Left$(sFilePathName, lThisChar) End If End If End Function
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder