MS Word VBA如何搜索所选文本并将其复制到段落的开头

时间:2015-02-06 10:58:57

标签: regex vba ms-word

我想搜索并复制段落中指定的年份并将其复制到段落的开头。以下是我正在使用的代码,它会选择年份,但不会将其复制到开头:

Sub CopyYeartoFirst()
'
' Macro1 Macro
'
'    Selection.Find.ClearFormatting
With ActiveDocument.Content
    With Selection.Find
        .Text = "[0-9]{4}"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
        .Execute
    End With
While .Find.Found = True

    Selection.Copy
    Selection.HomeKey Unit:=wdLine
    Selection.PasteAndFormat (wdPasteDefault)
    'Selection.TypeText Text:=" -- "
    .Find.Execute

    'Selection.Find.ClearFormatting
Wend


End With
End Sub

1 个答案:

答案 0 :(得分:0)

在粘贴搜索结果之前,您需要使用类似的内容

Dim oRng As Range
Set oRng = Selection.Paragraphs(1).Range
oRng.Collapse wdCollapseStart
oRng.Select