Count Files in a Directory

By | 2019-10-01

Given a valid path, this code will return the number of files in the specified directory.

Module

Option Explicit

'API constants
Public Const MAX_PATH = 260
Public Const INVALID_HANDLE_VALUE = -1
Public Const FILE_ATTRIBUTE_DIRECTORY = &H10

'API types
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

'API function calls
Public Declare Function FindFirstFile Lib "kernel32.dll" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Public Declare Function FindNextFile Lib "kernel32.dll" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Public Declare Function FindClose Lib "kernel32.dll" (ByVal hFindFile As Long) As Long
Public Function NumFiles(sPath As String) As Long
    Dim f As WIN32_FIND_DATA
    Dim hFile As Long

    NumFiles = 0
    'Add the wildchar to the search path
    If Right(sPath, 1) <> "\" Then sPath = sPath & "\"
    sPath = sPath & "*.*"
    'start a file enum in the specified path
    hFile = FindFirstFile(sPath, f)
    If hFile = INVALID_HANDLE_VALUE Then Exit Function
    'Exclude subdirectories from count
    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
    'Close the file search
    FindClose (hFile)
End Function

Usage

Private Sub Command1_Click()
    MsgBox NumFiles("c:\") & " Files in C:\"
End Sub

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.