Search code examples
vbams-word

wdCollapseEnd when selection extends to end of document


I am working on a VBA for Word program that reads paragraphs selected by the user, makes changes to them, then writes a new version after the existing selection. It works perfectly most of the time. The new data is written and the existing paragraphs are still highlighted as being selected.

A problem arises if the user selection extends to the end of the document. When the new lines are written the highlighted selection extends to incorporate them, resulting in the program going into an infinite loop.

Is it not possible to collapseend if at the end of the document? If not how do I add new lines to the end of the selection in that situation?

At the start of the program I do this:

Set docRange = Selection.Range
docRange.Collapse wdCollapseEnd
For Each paraRange In Selection.Paragraphs
' ...

I output the new data like this:

docRange.Text = outputline
docRange.Collapse wdCollapseEnd

Solution

  • Put this part before setting docRange

    If Selection.End = ActiveDocument.Content.End Then
        Selection.InsertParagraphAfter
        Selection.MoveEnd wdParagraph, -1
    End If
    

    It checks if the cursor is at the end of the document and adds a new paragraph where outputline is placed