CodeItBetter Programming Another VB Programming Blog

How to count number of sub-directories in a given directory (in two ways)

Posted on January 4, 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
'File/Folder Handling - How to count number of sub-directories in a given directory (in two ways)
Option Explicit
 
'Using Dir:

Public Function CountSubFoldersUsingDir(ByVal sPath As String) As Integer
    On Error Resume Next
    Dim dirname As String, iCount As Integer
    If Right$(sPath, 1) <> "\" Then sPath = sPath & "\"
    dirname = Dir$(sPath & "*.*", vbDirectory)
    Do While Len(dirname)
        If dirname = "." Or dirname = ".." Then
            ' Exclude the "." and ".." entries.
        ElseIf (GetAttr(sPath & dirname) And vbDirectory) = 0 Then
            ' This is a regular file.
        Else
            ' This is a directory.
            iCount = iCount + 1
        End If
        dirname = Dir$
    Loop
    CountSubFoldersUsingDir = iCount
End Function
 
'Using FSO:

Public Function CountSubFoldersUsingFSO(ByVal sPath As String) As Integer
    On Error Resume Next
    'Set a reference to "Microsoft Scripting Runtime"
    Dim FSO As Scripting.FileSystemObject
    Set FSO = New Scripting.FileSystemObject
    CountSubFoldersUsingFSO = FSO.GetFolder(sPath).SubFolders.count
    Set FSO = Nothing
End Function

Related posts:

  1. How to find whether the given directory is empty (in three ways)
  2. How to count number of files in a given directory (in two ways)
  3. How to list all sub directories names from the given directory
  4. How to list all sub directories in a given directory
  5. How to Copy the files to another directory (in three ways)
  6. How to remove directory (in Four ways)
  7. How to Move File from one directory to another (in three ways)
  8. How to list all files in a given directory
  9. How to Move Folder from one directory to another (in two ways)
  10. How to Copy Folder from one directory to another directory (in Two ways)

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.