Hi,
How to count the number of files in a given directory.
For example,
If I have 5 files in a directory called vbclassic. How can i count there are 5 files on that through code.
Show me the best way to do that.
Thanks
CS.
Printable View
Hi,
How to count the number of files in a given directory.
For example,
If I have 5 files in a directory called vbclassic. How can i count there are 5 files on that through code.
Show me the best way to do that.
Thanks
CS.
If you are not counting any subfolders then a simple loop with the Dir() function is enough
VB Code:
Dim F As String, counter As Integer F = Dir$("C:\vbclassic\*.*") Do While LenB(F) > 0 counter = counter + 1 F = Dir$ Loop MsgBox counter
casey.
The code Casey showed above will actually count the subfolders (not the content of these folders though) as well as the files. If you don't want the count the subfolders as files you have to check for that.VB Code:
Public Function CountFiles(ByVal sPath As String) As Long Dim nCounter As Long, sFile As String If Right$(sPath, 1) <> "\" Then sPath = sPath & "\" End If sFile = Dir$(sPath & "*.*", vbHidden + vbSystem) 'count system and hidden files as well Do While Len(sFile) 'it is a myth that LenB is faster then the Len function for dynamic strings If (GetAttr(sPath) And vbDirectory) <> vbDirectory Then nCount = nCount + 1 End If Loop CountFiles = nCount End Function
I have never known it to count the subfolders so i did a test on a folder that had subfolders and it didnt count them, i cant reproduce what you are saying.
casey.
You're correct Casey, the vbDirectory attribute must be set for the Dir function to include subdirectories... My bad.