2017-02-10 94 views
0

这可能很简单,但我无法使其工作。Word VBA:如何选择找到的文本而不是光标所在的位置

我需要搜索我的文档,找到包含字符串'alog'的单词并添加'ue'。例如,'目录' - >'目录'。

上面的工作正常,但我不能得到下一个工作:如果发现的字符串已经'后'日志'我不想再添加'ue'。

从宏访问的子程序如下。我已经尝试在'while execute'部分添加以下几行,但'selection'总是变成光标所在的单词。

With Selection 

    .Expand unit:=wdWord 

End With 

我怎样我)选择找到的范围的内容和ii)展开新的选择由两个字符来看看这两个字符是“UE”?

非常感谢。

Sub do_replace2(old_text As String, new_text As String, Count_changes As Integer) 

    ' Replaces 'log' with 'logue' 
    ' Ignores paragraphs in styles beginning with 'Question' 

    Dim rg As Range 
    Set rg = ActiveDocument.Range 

    With rg.Find 
    .Text = old_text 
    While .Execute 
     If Left(rg.Paragraphs(1).Style, 8) <> "Question" Then 
      rg.Text = new_text 
       With ActiveDocument.Comments.Add(rg, "Changed from '" & old_text & "'") 
       .Initial = "-logs" 
       .Author = "-logs" 
       End With 
       Count_changes = Count_changes + 1 
      End If 
    rg.Collapse wdCollapseEnd 
    Wend 
    End With 
    End Sub 

回答

0

我不太确定我是否遵循问题的第一部分“如何选择找到的范围的内容”。变量rg已包含搜索结果。如果你想选择它,只需使用rg.Select。这在调试时可能很有用(所以你可以看到Range在代码中的位置),但在你的问题的代码中没有其他原因使用Selection对象。您可以改用Range对象。

至于您的问题的第2部分“我如何......将新选择扩展两个字符”,您只需将.End的属性Range加2即可。

With rg.Find 
    .Text = old_text 
    While .Execute 
     If Left(rg.Paragraphs(1).Style, 8) <> "Question" Then 
      Dim test As Range 
      Set test = rg.Duplicate   'copy the found Range. 
      test.Collapse wdCollapseEnd  'move to the end of it. 
      test.End = test.End + 2   'expand to the next 2 characters. 
      If test.Text <> "ue" Then  'see if it's "ue". 
       rg.Text = new_text 
       With ActiveDocument.Comments.Add(rg, "Changed from '" & old_text & "'") 
        .Initial = "-logs" 
        .Author = "-logs" 
       End With 
       Count_changes = Count_changes + 1 
      End If 
     End If 
     rg.Collapse wdCollapseEnd 
    Wend 
End With 
+0

非常感谢共产国际:既然你只使用这一个测试(因为该.Find方法可以躲闪),在副本rg进行测试。那很完美。 – hmm

+0

谢谢共融;正如我所说的结束+ 2工作正常,给我一个范围开始(说)735和结束737与其中的字符串。但是,如果我执行.wdcollapsestart和.start + 5,范围的开始和结束是相同的,并且字符串为空。为什么'开始'和'结束'不一样? – hmm

+0

另一个更新:当我这样做: test.Collapse wdCollapseStart test.Start = test.Start - 5 它工作正常。你不能做'开始+ n'吗? – hmm

相关问题