`
xieyunbiao
  • 浏览: 38487 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

VBA遍历文件夹及子文件夹中所有文件

阅读更多

VBA中遍历文件方法很多,但很多方法又有局限,DIR的方法很难遍历子文件夹文件.FileSearch方法在office 2007中MS把Application对象FileSearch方法删除了.所有我们来用FileSystemObject对象实现遍历文件夹及子文件夹中所有文件.

代码如下:

 Dim arrFiles()
 Dim countFiles%
 Public Sub ListAllFiles()
    
         Dim strPath$
         Dim i%
         Dim fso As New FileSystemObject, fd As Folder

         strPath = "C:\temp"
         ReDim arrFiles(1 To 1000)
         cntFiles = 0
         Set fd = fso.GetFolder(strPath)
         SearchFiles fd
         ReDim Preserve arrFiles(1 To countFiles)
         For i = 1 To cntFiles
            Msgbox arrFiles(i)
         Next i
 End Sub

 Sub SearchFiles(ByVal fd As Folder)
     Dim fl As File
     Dim sfd As Folder
   
     For Each fl In fd.Files
       countFiles= countFiles+ 1
       If cntFiles > UBound(arrFiles) Then ReDim Preserve arrFiles(1 To countFiles+ 1000)

      arrFiles(cntFiles) = fl.Path
     Next fl
   
     If fd.SubFolders.Count = 0 Then Exit Sub
   
     For Each sfd In fd.SubFolders
       SearchFiles sfd
     Next
   
 End Sub

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics