|
请楼主参考:
- Sub DIR_循环遍历文件夹()
- On Error Resume Next
- Dim objShell As Object, objFolder As Object, SearchPath$, DicList As Object, FileList As Object, Key, NowDic$, NowFile$, i&, FileName, FilePath, doc As Document, x&
- Set objShell = CreateObject("Shell.Application")
- Set objFolder = objShell.BrowseForFolder(0, "请选择文件夹!", 0, 0)
- SearchPath = objFolder.self.Path & ""
- Set objShell = Nothing
- Set objFolder = Nothing
- If MsgBox("请确认!是否处理文件夹 " & SearchPath & " ?", 4 + 16) = vbNo Then Exit Sub
- 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
- 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
- Sub FSO_循环遍历文件夹()
- On Error Resume Next
- Dim objShell As Object, objFolder As Object, pPath$, f As Object, fd As Object, fso As Object, Stack$(), top&, n&, stxt$, doc As Document, x&
- Set objShell = CreateObject("Shell.Application")
- Set objFolder = objShell.BrowseForFolder(0, "请选择文件夹!", 0, 0)
- pPath = objFolder.self.Path & ""
- Set objShell = Nothing
- Set objFolder = Nothing
- If MsgBox("请确认!是否处理文件夹 " & pPath & " ?", 4 + 16) = vbNo Then Exit Sub
- Set fso = CreateObject("Scripting.FileSystemObject")
- top = 1
- ReDim Stack(0 To top)
- Do While top >= 1
- For Each f In fso.GetFolder(pPath).Files
- n = n + 1
- stxt = f.Path
- If stxt Like "*.doc*" Then
- Set doc = Documents.Open(FileName:=stxt, Visible:=False)
- doc.Content.Font.Color = wdColorRed '单个文档处理
- doc.Close savechanges:=wdSaveChanges
- x = x + 1
- End If
- Next
- For Each fd In fso.GetFolder(pPath).SubFolders
- Stack(top) = fd.Path
- top = top + 1
- If top > UBound(Stack) Then ReDim Preserve Stack(0 To top)
- Next
- If top > 0 Then pPath = Stack(top - 1): top = top - 1
- Loop
- Set f = Nothing
- Set fd = Nothing
- Set fso = Nothing
- MsgBox "文件夹包含 " & n & " 个文件!" & vbCr & "共处理 Word 文档(*.docx/*.doc) " & x & " 个!", 0 + 48
- End Sub
复制代码 |
|