问题描述:

I'm using Range.Find to find a specific string in a document. When I find this string I want to look at the character BEFORE this string. I had an idea to get the range as selection and then use the Selection.MoveLeft = 1 but I really can't find how to get the range as selection. This is the code I have:

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

网友答案:

Solution

Here is my solution.

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

Hope this helps.

网友答案:

Here's a way you can do it without Selecting

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
相关阅读:
Top