vba - 拆分 MailMerge 文档:为什么最后一个文档是空的?
问题描述
标题说明了一切——主要是。这是我的第一个 Word 宏。
我尝试将 MailMerge 的结果拆分为单独的文件。逻辑对我来说似乎很好,但最后一个文档总是空的。知道为什么吗?
我注意到合并文档的末尾没有节标记。激活 MailMerge 文档时调用宏。
Sub SplitDoc()
Dim sec As Section, doc As Document, fn As String
Dim targetfolder As String
targetfolder = "Y:\\" 'ignore this :-)
For Each sec In ActiveDocument.Sections
sec.Range.Copy
Set doc = Documents.Add
doc.Range.Paste
fn = Mid(Split(doc.Paragraphs(3).Range.Text, ", ")(0), 5)
Debug.Print Now, fn
'Removes the break that is copied at the end of the section, if any.
With doc.Sections.Last.Range
.MoveStart wdCharacter, -1
'============= here is the issue:
'for the last section (without ending section mark)
.Delete 'it deletes the empties the whole doc
End With
'restore page setup that was stored in the section break
With doc.PageSetup
.TopMargin = CentimetersToPoints(2)
.BottomMargin = CentimetersToPoints(2)
.LeftMargin = CentimetersToPoints(2)
.RightMargin = CentimetersToPoints(2)
End With
doc.SaveAs FileName:=fn & ".docx"
doc.Close
Set doc = Nothing
Next sec
Debug.Print Now, "Done"
End Sub
解决方案
当不存在分节符时,在输出文档末尾删除分节符的代码正在清空文档。
With doc.Sections.Last.Range
.MoveStart wdCharacter, -1
.Delete
End With
取而代之
With Selection.Find
.Text = "^b"
.Replacement.Text = ""
.Execute Replace:=wdReplaceAll
End With
推荐阅读
- django - Django:从视图或从模板访问数据库(使用模板语言)在性能上是否存在差异?
- leaflet - 如何同时切换标记和工具提示的不透明度?
- python - np.dot 为 Dataframe(float64) 和 np.ndarray(fload64) 返回 nan
- python - 不能在 python 3.7.9 中使用带有 importlib 的内置函数
- c# - 将 JSON 请求转换为 C# 对象并以不同的 JSON 格式发送回响应
- python - Jinja - 如果声明不起作用 - 请帮助我
- python - 如何有条件地传递不同的参数
- javascript - 使用 Nodemailer 和 HTML - 在 HTML 中循环
- git - 单个文件定期更改时的 Git 最佳实践?
- prolog - Prolog:将数字分解为数字