如何在Word文档中选择整行文本

问题描述

我不仅要复制字符串匹配项(“表 1234”),还要在同一行中包含字符串的其余部分。 (“表 1234 - 此处的剩余文本”)。

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

解决方法

根据我的评论,Word 模型没有“Line”对象。但是...... selection.move 有一个 units:=WdUnits.Line 参数来按行移动选择......(谷歌告诉我)

那么你可以这样做(免责声明:它很粗糙,准备好了,可能不健壮)

' 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()

以下是我搜索“嵌入”一词并选择第 2 行的示例: enter image description here

,
public function ReturnLineOfTable() as string
    dim txt as string = ...
    
    for each Line in txt.split(environment.newline)
       'If regex is found then
           Return Line
       ' End if
    next
end function