(Solved) – Why is this VBA Code not saving and restoring the Selection correctly

(solved)-–-why-is-this-vba-code-not-saving-and-restoring-the-selection-correctly

I’ve been trying to use Visual Basic to take every line of text in a Word Document and format it in a certain way depending on the content of the text.

The way I am trying to achieve this is:
1. save the current selection of text
2. find the number of lines in the selection
3. iterate through those lines by selecting one line at a time
4. modifying the line
5. at the end, restore the original selection

I’ve reduced my code to a minimal example of the issue.

Sub ReplaceText()
    ' Save the original selection
    Dim original As range
    Set original = Selection.range

    ' Get the number of lines in the selection
    Dim lines As Long
    With Dialogs(wdDialogToolsWordCount)
        .Execute
        lines = .lines
    End With

    ' Iterate through each line
    For Index = 1 To lines
        ' Go to beginning of line
        Selection.HomeKey Unit:=wdLine
        ' Select the entire line
        Selection.Expand wdLine
        ' Save the text of the line
        Dim line
        line = Selection.Text

        ' Line with the problem
        ' Just setting the selection text back to itself
        Selection.Text = line

        ' Advance cursor to next Line
        Selection.MoveDown Unit:=wdLine
    Next Index

    ' Restore the original selection
    original.Select
End Sub

The issue is that when the original selection is restored at the end, it doesn’t restore properly. The restored selection selects everything from the original selection except for the last line. I’m not really sure why this happens.

Leave a Reply

Your email address will not be published. Required fields are marked *