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
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.