Results 1 to 5 of 5

Thread: How to count the number of files in a given directory?

  1. #1

    Thread Starter
    Frenzied Member cssriraman's Avatar
    Join Date
    Jun 2005
    Posts
    1,465

    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.
    CS

  2. #2
    Fanatic Member vbasicgirl's Avatar
    Join Date
    Jan 2004
    Location
    Manchester, UK
    Posts
    1,016

    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:
    1. Dim F As String, counter As Integer
    2.  
    3. F = Dir$("C:\vbclassic\*.*")
    4.  
    5. Do While LenB(F) > 0
    6.    counter = counter + 1
    7.   F = Dir$
    8. Loop
    9.  
    10. MsgBox counter

    casey.

  3. #3
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    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:
    1. Public Function CountFiles(ByVal sPath As String) As Long
    2.     Dim nCounter As Long, sFile As String
    3.     If Right$(sPath, 1) <> "\" Then
    4.         sPath = sPath & "\"
    5.     End If
    6.     sFile = Dir$(sPath & "*.*", vbHidden + vbSystem) 'count system and hidden files as well
    7.     Do While Len(sFile) 'it is a myth that LenB is faster then the Len function for dynamic strings
    8.         If (GetAttr(sPath) And vbDirectory) <> vbDirectory Then
    9.             nCount = nCount + 1
    10.         End If
    11.     Loop
    12.     CountFiles = nCount
    13. End Function

  4. #4
    Fanatic Member vbasicgirl's Avatar
    Join Date
    Jan 2004
    Location
    Manchester, UK
    Posts
    1,016

    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.

  5. #5
    I'm about to be a PowerPoster! Joacim Andersson's Avatar
    Join Date
    Jan 1999
    Location
    Sweden
    Posts
    14,649

    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
  •  



Click Here to Expand Forum to Full Width