VBA - 获取选择范围

时间:2014-08-13 09:06:38

标签: vba ms-word selection word-vba

我使用Range.Find在文档中查找特定字符串。当我找到这个字符串时,我想看看字符串之前的字符。我有一个想法,让范围作为选择,然后使用Selection.MoveLeft = 1,但我真的无法找到如何获得范围作为选择。这是我的代码:

Private Function abc() As Boolean
    Set rng = ActiveDocument.Range
    With rng.Find
        .MatchWildcards = True
        Do While .Execute(findText:="123456", Forward:=False) = True
            MsgBox (rng.Text)
            Set Selection = rng 'Set the selection from range
            MsgBox (Selection.Text)
            Selection.MoveLeft = 1 'Move the selection
            MsgBox (Selection.Text)
        Loop
    End With
    abc = True
End Function

2 个答案:

答案 0 :(得分:0)

解决方案

这是我的解决方案。

Sub testhis()

    Set rng = ActiveDocument.Range

        With rng.Find
        .MatchWildcards = True
            Do While .Execute(findText:="123456", Forward:=False) = True
                rng.Select
                Selection.MoveLeft Unit:=wdCharacter, Count:=2
                MsgBox (Selection.Text)

            Loop
        End With


End Sub

希望这会有所帮助。

答案 1 :(得分:0)

这是一种无需选择

即可实现的方法
Sub abc()

    Dim rng As Range

    Set rng = ActiveDocument.Range

    With rng.Find
        .MatchWildcards = True
        Do While .Execute(findText:="123456", Forward:=False) = True
            MsgBox rng.Text

            rng.Move wdCharacter, -2
            rng.Expand wdCharacter

            MsgBox rng.Text
        Loop
    End With


End Sub