Search code examples
vb.netms-wordcopyrangeword-interop

How to Select Full Line of Text in Word Document


I would like to not only copy the string match ("Table 1234"), but also include the rest of the string on the same line. ("Table 1234 - remaining text here").

Dim rng As Word.Range = oWord.ActiveDocument.Range

rng.Find.ClearFormatting()
rng.Find.Text = "Table [0-9]{3}"
rng.Find.MatchWildcards = True
Do While rng.Find.Execute(Forward:=True) = True
     rng.Copy()
     rng.Collapse(WdCollapseDirection.wdCollapseEnd)
Loop

Solution

  • As per my comment, the Word model does not have a 'Line' object. But ... the selection.move has a units:=WdUnits.Line parameter to move the selection by line ... (Google told me)

    So then you can do this (disclaimer: it's rough and ready and probably not robust)

    ' select the found text and go up one line and collapse the selection to the end 
    ' that gives you the starting position of the next line of text
    ' that's the line that has the fount text
    rng.Select
    Selection.Move(Unit:=WdUnits.wdLine, Count:=-1)
    
    Selection.Collapse(WdCollapseDirection.wdCollapseEnd)
    Dim startPos As Integer = Selection.End
    
    ' Now do same for the end position of the line of text that has the found text
    rng.Select()
    Selection.Move(Unit:=WdUnits.wdLine, Count:=1)
    
    Selection.Collapse(WdCollapseDirection.wdCollapseStart)
    Dim endPos As Integer = Selection.Start
    
    Selection.SetRange(startPos, endPos)
    Selection.Select()
    

    Below is an example in which I search the word 'embed' and line 2 is selected: enter image description here