首页 > 解决方案 > 拆分 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

标签: vbams-word

解决方案


当不存在分节符时,在输出文档末尾删除分节符的代码正在清空文档。

        With doc.Sections.Last.Range
            .MoveStart wdCharacter, -1
            .Delete
        End With  

取而代之

        With Selection.Find
            .Text = "^b"
            .Replacement.Text = ""
            .Execute Replace:=wdReplaceAll
        End With

推荐阅读