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

Microsoft Office VBA 专栏收录该内容
18 篇文章 0 订阅

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

  • 0
    点赞
  • 1
    评论
  • 7
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
<div style="white-space: pre-wrap; line-height: 1.75; font-size: 14px;">这个系列课程会深入讲解Python的各种核心技术的原理和实现。这些技术是对我从事多年Python开发和教学经验的总结,以及很多学员和一线开发人员在工作和学习遇到的各种技术问题的搜集和整理。同时还包含了各大技术论坛和问答社区(如stack overflow)的精彩问题的回答的总结和引申。</div> <p><!--5f39ae17-8c62-4a45-bc43-b32064c9388a:W3siYmxvY2tJZCI6IjQ1MTctMTYwMjQ4NTg4NzU1MCIsImJsb2NrVHlwZSI6InBhcmFncmFwaCIsInN0eWxlcyI6eyJhbGlnbiI6ImxlZnQiLCJpbmRlbnQiOjAsInRleHQtaW5kZW50IjowLCJsaW5lLWhlaWdodCI6MS43N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oYXIiOiLvvIwifSx7ImNoYXIiOiLmiJEifSx7ImNoYXIiOiLku6wifSx7ImNoYXIiOiLlsLEifSx7ImNoYXIiOiLlhYgifSx7ImNoYXIiOiLku44ifSx7ImNoYXIiOiJQIn0seyJjaGFyIjoieSJ9LHsiY2hhciI6InQifSx7ImNoYXIiOiJoIn0seyJjaGFyIjoibyJ9LHsiY2hhciI6Im4ifSx7ImNoYXIiOiLnlJ8ifSx7ImNoYXIiOiLmiJAifSx7ImNoYXIiOiLlmagifSx7ImNoYXIiOiLmnaUifSx7ImNoYXIiOiLlvIAifSx7ImNoYXIiOiLlp4sifSx7ImNoYXIiOiLov5kifSx7ImNoYXIiOiLkuIAifSx7ImNoYXIiOiLns7sifSx7ImNoYXIiOiLliJcifSx7ImNoYXIiOiLor74ifSx7ImNoYXIiOiLnqIsifSx7ImNoYXIiOiLnmoQifSx7ImNoYXIiOiLlraYifSx7ImNoYXIiOiLkuaAifSx7ImNoYXIiOiLjgIIifV0sImlzUmljaFRleHQiOnRydWUsImtlZXBMaW5lQnJlYWsiOnRydWV9fV0=--></p>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值