|
-
May 20th, 2006, 10:46 AM
#1
Thread Starter
Frenzied Member
How to count the number of files in a given directory?
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.
-
May 20th, 2006, 10:58 AM
#2
Re: How to count the number of files in a given directory?
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.
-
May 20th, 2006, 11:31 AM
#3
Re: How to count the number of files in a given directory?
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
-
May 20th, 2006, 12:11 PM
#4
Re: How to count the number of files in a given directory?
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.
-
May 20th, 2006, 12:34 PM
#5
Re: How to count the number of files in a given directory?
You're correct Casey, the vbDirectory attribute must be set for the Dir function to include subdirectories... My bad.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|