|
* 据网文称,VBA遍历文件夹常用有三种方法,这三种方法中,filesearch不适合2007和2010版本,而且速度比较慢;递归法FSO速度也慢;只有用DIR加循环(+双字典+数组)的方法,速度飞快。
* 我决定抛弃 Word2003 的 FileSearch 法,FSO法也慢也不用,采用 Dir + 循环 + 双字典 + 数组 的方法。
* 从网上找了一段代码,原作者是 kiddragon,在此表示感谢!虽然不懂字典、数组,但我仍做了一些修改。
* 下面的代码在 Word2007/2003 中测试通过,运行正常(测试了包含 25 个文件和 62 个文件的文件夹)!
——请各位老师、朋友指教,是否还有更好、更快的方法?
- Sub LoopDir循环遍历文件夹()
- On Error Resume Next
- Dim objShell As Object
- Dim objFolder As Object
- Dim SearchPath As String
- Set objShell = CreateObject("Shell.Application")
- Set objFolder = objShell.BrowseForFolder(0, "请选择文件夹!", 0, 0)
- SearchPath = objFolder.self.Path & ""
- If MsgBox("请确认!是否处理文件夹 " & SearchPath & " ?", 4 + 16) = vbNo Then Exit Sub
- Set objShell = Nothing
- Set objFolder = Nothing
- Dim DicList As Object
- Dim FileList As Object
- Dim Key
- Dim NowDic As String
- Dim NowFile As String
- Dim i As Long
- Dim FileName, FilePath
- Set DicList = CreateObject("Scripting.Dictionary")
- Set FileList = CreateObject("Scripting.Dictionary")
- DicList.Add SearchPath, ""
- i = 0
- Do While i < DicList.Count
- Key = DicList.keys
- NowDic = Dir(Key(i), vbDirectory)
- Do While NowDic <> ""
- If (NowDic <> ".") And (NowDic <> "..") Then
- If (GetAttr(Key(i) & NowDic) And vbDirectory) = vbDirectory Then DicList.Add Key(i) & NowDic & "", ""
- End If
- NowDic = Dir()
- Loop
- i = i + 1
- Loop
- For Each Key In DicList.keys
- NowFile = Dir(Key)
- Do While NowFile <> ""
- FileList.Add NowFile, Key
- NowFile = Dir()
- Loop
- Next
- Dim doc As Document
- Dim x&
- i = 0
- FileName = FileList.keys
- FilePath = FileList.Items
- Do While i < FileList.Count
- If FilePath(i) & FileName(i) Like "*.doc*" Then
- Set doc = Documents.Open(FileName:=FilePath(i) & FileName(i), Visible:=False)
- doc.Content.Font.Color = wdColorRed '单个文档处理
- doc.Close SaveChanges:=wdSaveChanges
- x = x + 1
- End If
- i = i + 1
- Loop
- Set DicList = Nothing
- Set FileList = Nothing
- MsgBox "文件夹包含 " & i & " 个文件!" & vbCr & "共处理 Word 文档(*.docx/*.doc) " & x & " 个!", 0 + 48
- End Sub
复制代码 |
|