Word宏开始从文档开始查找和替换,但将光标返回到上一个位置

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (112)

我有一个查找和替换宏,在一个句子的结尾和另一个句子的开头之间添加一个空格。当我在单词中移动句子时,有时会发生这种情况。我注意到,如果光标位于标点符号的任一侧,则宏无法看到“查找”模式并且无法修复它。我认为这是因为查找和替换从光标位置开始搜索。有没有办法调整代码,所以它也找到它们?我知道我可以告诉宏从头开始,但我更倾向于将光标留在当前位置,特别是如果我在一个长文档的末尾附近运行它。

Sub AddOneSpaceBetweenSentences()
' AddOneSpaceBetweenSentences Macro
'
 With Selection.Find
 .Forward = True
 .Text = "(?)([.\?\!])([A-Z])"
 .ClearFormatting
 .Replacement.Text = "\1\2 \3" 'there is a space between \2 and \3
 .MatchWildcards = True
 .Wrap = wdFindContinue
 .Execute Replace:=wdReplaceAll

End With

End Sub
提问于
用户回答回答于

要么只是将选择范围扩大2个字符......

If Selection.Start > 10 Then
    Selection.Previous(Unit:=wdCharacter, Count:=2).Select
End If

......或者这样做:

Sub AddOneSpaceBetweenSentences()
    Dim SearchText As String
    Dim ReplaceText As String

    ' extend selection by 1 character
    If Selection.Start > 0 Then
        Selection.Previous(Unit:=wdCharacter, Count:=1).Select
    End If
    Selection.Collapse

    ' adapt search & replace pattern    
    If InStr(1, ".?!", Selection.Characters(1), vbBinaryCompare) > 0 Then
        SearchText = "([.\?\!])([A-Z])"
        ReplaceText = "\1 \2"
    Else
        SearchText = "(?)([.\?\!])([A-Z])"
        ReplaceText = "\1\2 \3"
    End If

    With Selection.Find
        .Forward = True
        .text = SearchText
        .ClearFormatting
        .Replacement.text = ReplaceText
        .MatchWildcards = True
        .Wrap = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With
End Sub
用户回答回答于

最可靠的方法是使用Range对象而不是Selection。使用Range文档中的选择时不会更改。

  Sub AddOneSpaceBetweenSentences()
    ' AddOneSpaceBetweenSentences Macro
    '
     Dim rng as Word.Range

     Set rng = ActiveDocument.Content
     With rng.Find
       .Forward = True
       .Text = "(?)([.\?\!])([A-Z])"
       .ClearFormatting
       .Replacement.Text = "\1\2 \3" 'there is a space between \2 and \3
       .MatchWildcards = True
       .Wrap = wdFindContinue
       .Execute Replace:=wdReplaceAll
    End With

  End Sub

扫码关注云+社区

领取腾讯云代金券