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

时间:2019-02-21 18:16:32

标签: vba ms-word

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

hashchange

3 个答案:

答案 0 :(得分:1)

真的有必要在结束符前加一个字符。要么 ?或!
如果没有,只需将"([.\?\!])([A-Z])"替换为"\1 \2"


简单尝试:只需将选择范围向左扩展2个字符即可。

如果光标位于文档的前两个字符上,则会出现错误。为了防止这种情况并防止字符计数,我只使用了Selection.Start > 10

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

    ' if selection begins directly before end of sentence (.?!)
    ' 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

答案 1 :(得分:1)

最可靠的方法是使用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

答案 2 :(得分:1)

更好:

Sub AddOneSpaceBetweenSentences()
Application.ScreenUpdating = False
With ActiveDocument.Range.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Forward = True
  .Format = False
  .MatchWildcards = True
  .Wrap = wdFindContinue
  .Text = "([.\?\!])([A-Z])"
  .Replacement.Text = "\1 \2"
  .Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub