|
* Word2003 用 FileSearch 对象可以达成目标,但最近我发现一是太慢,二是似乎宏有时不运行了。
* 在网上找了很多 FSO(递归)和用 DIR 函数(包括双字典)的方法,但均未达到目的。
* 下面是捷克人编程的 VBA 宏,能够循环遍历文件夹及子文件夹中文件,在 Word2003 中我已经测试通过,并且我已经将 6000 来个 Word 文档极速地转换为 TXT 纯文本文档作为资料来保存。有需要的朋友可以试用此宏,但要注意:操作前保留备份及核查文件数目、内容。
- Sub 批量转换doc2txt_dir()
- On Error Resume Next
- Dim fd As FileDialog, p$, doc As Document, n&
- Set fd = Application.FileDialog(msoFileDialogFolderPicker)
- If fd.Show = -1 Then p = fd.SelectedItems(1) Else End
- Set fd = Nothing
- If MsgBox("是否转换文件夹 " & p & " ?", 4 + 48) = vbNo Then End
- Dim FileNameWithPath As Variant, ListOfFilenamesWithParh As New Collection
- Call FileSearchByHavrda(ListOfFilenamesWithParh, p, "*.doc", True)
- For Each FileNameWithPath In ListOfFilenamesWithParh
- Set doc = Documents.Open(FileName:=FileNameWithPath, Visible:=False)
- With doc
- .SaveAs FileName:=Left(FileNameWithPath, Len(FileNameWithPath) - 4), FileFormat:=wdFormatText
- .Close
- End With
- n = n + 1
- Next FileNameWithPath
- If ListOfFilenamesWithParh.Count = 0 Then MsgBox "File not found!"
- MsgBox "转换完毕!共转换 " & n & " 个文档!", 0 + 48
- End Sub
- Sub FileSearchByHavrda(pFoundFiles As Collection, pPath As String, pMask As String, pIncludeSubdirectories As Boolean)
- Dim DirFile As String, CollectionItem As Variant, SubDirCollection As New Collection
- pPath = Trim(pPath)
- If Right(pPath, 1) <> "" Then pPath = pPath & ""
- DirFile = Dir(pPath & pMask)
- Do While DirFile <> ""
- pFoundFiles.Add pPath & DirFile
- DirFile = Dir
- Loop
- If Not pIncludeSubdirectories Then Exit Sub
- DirFile = Dir(pPath & "*", vbDirectory)
- Do While DirFile <> ""
- If DirFile <> "." And DirFile <> ".." Then If ((GetAttr(pPath & DirFile) And vbDirectory) = 16) Then SubDirCollection.Add pPath & DirFile
- DirFile = Dir
- Loop
- For Each CollectionItem In SubDirCollection
- Call FileSearchByHavrda(pFoundFiles, CStr(CollectionItem), pMask, pIncludeSubdirectories)
- Next
- End Sub
复制代码 |
|