CodeItBetter Programming Another VB Programming Blog

How to count number of files 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
35
36
'File/Folder Handling - How to count number of files in a given directory (in two ways)
Option Explicit
 
'Using Dir:

Public Function CountFilesUsingDir(ByVal sPath As String) As Integer
    On Error Resume Next
    Dim iCount As Integer
    sPath = Dir$(sPath)
    Do While Len(sPath) > 0
        iCount = iCount + 1
        sPath = Dir$
    Loop
    CountFilesUsingDir = iCount
End Function
'How can I call this function:
'Debug.Print CountFilesUsingDir("C:\Temp\b\*.xml") 
'Will display the count of *.xml files in C:\temp\b folder
'Debug.Print CountFilesUsingDir("C:\Temp\b\")      
'Will display the count of *.* files in C:\temp\b folder

'Using FSO:

Public Function CountFilesUsingFSO(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
    CountFilesUsingFSO = FSO.GetFolder(sPath).Files.Count
    Set FSO = Nothing
End Function
'How can I call this function:
'Debug.Print CountFilesUsingFSO("C:\Temp\b\*.xml") 
'Will display the count of *.xml files in C:\temp\b folder
'Debug.Print CountFilesUsingFSO("C:\Temp\b\")      
'Will display the count of *.* files in C:\temp\b folder
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.