|
经改动后,又管事了,说明原来的 DIR + 双字典 循环文件夹 代码是没有问题的,只能说单个文档部分是我没做好,也 谢谢 sylun 老师 来救急! 改动后的代码,楼主看看是否运行正确:
- 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)
- With doc
- .Content.InsertBefore Text:=Left(.Name, Len(.Name) - 5) & vbCr
- With .Paragraphs(1).Range
- .Style = wdStyleHeading1
- With .Font
- .Size = 22
- .Color = wdColorAutomatic
- End With
- With .ParagraphFormat
- .SpaceBefore = 30
- .SpaceAfter = 30
- .Alignment = wdAlignParagraphCenter
- End With
- End With
- .Close SaveChanges:=wdSaveChanges
- End With
- 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
复制代码 |
|