How to find the number of files in the Directory
Posted on January 5, 2009
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 'File/Folder Handling - How to find the number of files in the Directory Option Explicit Public Const MAX_PATH = 260 Public Const INVALID_HANDLE_VALUE = -1 Public Const FILE_ATTRIBUTE_DIRECTORY = &H10 Public Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type Public Type WIN32_FIND_DATA dwFileAttributes As Long ftCreationTime As FILETIME ftLastAccessTime As FILETIME ftLastWriteTime As FILETIME nFileSizeHigh As Long nFileSizeLow As Long dwReserved0 As Long dwReserved1 As Long cFileName As String * MAX_PATH cAlternate As String * 14 End Type Public Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As _ String, lpFindFileData As WIN32_FIND_DATA) As Long Public Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, _ lpFindFileData As WIN32_FIND_DATA) As Long Public Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long Public Function NumFiles(ByVal sPath As String) As Long Dim f As WIN32_FIND_DATA Dim hFile As Long NumFiles = 0 If Right(sPath, 1) <> "\" Then sPath = sPath & "\" sPath = sPath & "*.*" hFile = FindFirstFile(sPath, f) If hFile = INVALID_HANDLE_VALUE Then Exit Function If (f.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY) = 0 Then NumFiles = 1 Do While FindNextFile(hFile, f) If (f.dwFileAttributes And FILE_ATTRIBUTE_DIRECTORY) = 0 Then NumFiles = NumFiles + 1 Loop FindClose (hFile) End Function 'How can I call this function: Private Sub Form_Load() Call MsgBox(NumFiles("C:\Windows\Temp") & " Files in C:\Windows\Temp") End Sub |