【发布时间】:2017-12-21 18:11:32
【问题描述】:
我有很多带有不同标题的 word 文件 (~5000),我用宏读取了这些文件,并将这些放在文件夹中的多个 word 文档合并到一个文档中。
这里是相关代码:
Sub MergeDocs()
Dim rng As Range
Dim MainDoc As Document
Dim strFile As String, strFolder As String
Dim Count As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Pick folder"
.AllowMultiSelect = False
If .Show Then
strFolder = .SelectedItems(1) & Application.PathSeparator
Else
Exit Sub
End If
End With
Set MainDoc = Documents.Add
strFile = Dir$(strFolder & "*.doc") ' can change to .docx
Count = 0
Do Until strFile = ""
Count = Count + 1
Set rng = MainDoc.Range
With rng
.Collapse wdCollapseEnd
If Count > 1 Then
.InsertBreak wdSectionBreakNextPage
.End = MainDoc.Range.End
.Collapse wdCollapseEnd
End If
.InsertFile strFolder & strFile
End With
strFile = Dir$()
Loop
MsgBox ("Files are merged")
lbl_Exit:
Exit Sub
End Sub
它正在工作,但是当我尝试将文件另存为 .txt 时,页眉+页脚丢失了。有什么方法可以将此页眉部分也保存到 .txt 文件中吗? (正如我所写,每个文档都有不同的标题。)
编辑:
Sub MergeDocs()
Dim rng As Range
Dim MainDoc As Document
Dim strFile As String, strFolder As String
Dim Count As Long
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Pick folder"
.AllowMultiSelect = False
If .Show Then
strFolder = .SelectedItems(1) & Application.PathSeparator
Else
Exit Sub
End If
End With
Set MainDoc = Documents.Add
strFile = Dir$(strFolder & "*.doc") ' can change to .docx
Count = 0
Dim doc As Document
Dim head As String, foot As String
Do Until strFile = ""
Set doc = Documents.Open(strFile)
head = doc.Sections(1).Headers(wdHeaderFooterPrimary).Range.Text
foot = doc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text
doc.Close False
Count = Count + 1
Set rng = MainDoc.Range
With rng
.Collapse wdCollapseEnd
If Count > 1 Then
.InsertBreak wdSectionBreakNextPage
.End = MainDoc.Range.End
.Collapse wdCollapseEnd
End If
.InsertAfter head
.InsertParagraphAfter
.InsertFile strFolder & strFile
.InsertAfter foot
End With
strFile = Dir$()
Loop
MsgBox ("Files are merged")
lbl_Exit:
Exit Sub
End Sub
【问题讨论】:
-
到目前为止,您不会在将文件附加到主文档之前打开它们。你将不得不这样做。然后-假设您只有一个页眉/页脚-您可以将页眉和页脚读入如下变量:
head = doc.Sections(1).Headers(wdHeaderFooterPrimary).Range.text和foot = ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).Range.text并在.InsertFile之后分别插入这些文本。这是你需要的吗? -
是的,我需要这个逻辑!因为在标题部分我得到了例如我需要的日期部分,当然它在所有 word 文档中都是不同的。它在代码中的外观如何?你能写一个答案吗?我可以尝试并接受它!
标签: vba ms-word type-conversion