除了可以遍历所有的驱动器,你也可以遍历某个文件夹下的所有文件。这在当你需要在整个驱动器中查找特定的文件的时候特别有用。Recursion is also very helpful in these cases since you need to keep performing the same action as you work your way down the tree. 下面这段代码用来统计所有GIF文件的个数。它也可以很容易的修改成文件列表,对特定的文件做指定的操作,等等。其中的关键在于目录数的遍历: Option Explicit Dim m_lngFileCount As Long '定义计数器 Dim m_objFSO As Scripting.FileSystemObject '定义文件系统对象
Sub Main() Set m_objFSO = New Scripting.FileSystemObject m_lngFileCount = 0 CheckFolder "C:\" Debug.Print "C盘下GIF文件总数: " & m_lngFileCount End Sub
Sub CheckFolder(strPath As String) Dim objFolder As Scripting.Folder '文件夹对象 Dim objFile As Scripting.File '文件对象 Dim objSubdirs As Scripting.Folders '文件夹集合对象 Dim objLoopFolder As Scripting.Folder '文件夹对象
Debug.Print "Checking directory " & strPath Set objFolder = m_objFSO.GetFolder(strPath)
' 检查目录中的文件 For Each objFile In objFolder.Files If UCase$(Right$(objFile.ShortPath, 4)) = ".GIF" Then '这一段是条件检查,但找到的文件是否符合给定的条件,这儿通过取文件名的 '最后4位看是不是“.GIF“来判断文件是否是GIF文件。 m_lngFileCount = m_lngFileCount + 1 '找到指定条件的文件后进行相应的操作,这儿是把计数器加一。 End If Next objFile
' 在所有子目录中循环,计数。 Set objSubdirs = objFolder.SubFolders For Each objLoopFolder In objSubdirs CheckFolder objLoopFolder.Path '递归调用CheckFolder子过程,实现目录树的遍历。 Next objLoopFolder