MS Word VBA 如何搜索并将选定的文本复制到段落的开头
MS Word VBA How to Search and copy selected text to beginning of the Paragraph
我想搜索并复制段落中指定的年份并将其复制到段落的开头。以下是我正在使用的代码,它确实选择了年份但没有将其复制到开头:
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
在粘贴搜索结果之前,您需要使用类似的东西
Dim oRng As Range
Set oRng = Selection.Paragraphs(1).Range
oRng.Collapse wdCollapseStart
oRng.Select
我想搜索并复制段落中指定的年份并将其复制到段落的开头。以下是我正在使用的代码,它确实选择了年份但没有将其复制到开头:
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
在粘贴搜索结果之前,您需要使用类似的东西
Dim oRng As Range
Set oRng = Selection.Paragraphs(1).Range
oRng.Collapse wdCollapseStart
oRng.Select