Разделение документа MailMerge: почему последний документ пуст? - PullRequest
0 голосов
/ 31 октября 2018

Название говорит само за себя - в основном. Это мой первый макрос 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

1 Ответ

0 голосов
/ 31 октября 2018

Код для удаления разрыва раздела в конце выходного документа очищал документ при отсутствии разрыва раздела.

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

заменено на

        With Selection.Find
            .Text = "^b"
            .Replacement.Text = ""
            .Execute Replace:=wdReplaceAll
        End With
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...