Arcus
Arcus

Reputation: 51

Word VBA: How to replace only the next instance of a string via Replacement Object

This is a silly question, but can't figure it out.

Straight from the Microsoft Site:

This example finds every instance of the word "Start" in the active document and replaces it with "End." The find operation ignores formatting but matches the case of the text to find ("Start").

Set myRange = ActiveDocument.Range(Start:=0, End:=0)
 With myRange.Find
.ClearFormatting
.Text = "Start"
With .Replacement
    .ClearFormatting
    .Text = "End"
End With
.Execute Replace:=wdReplaceAll, _
    Format:=True, MatchCase:=True, _
    MatchWholeWord:=True
End With

I need to know how to make it so it only finds the next instance of Start and replace it with End. This will leave all other Ends intact throughout the document.

Upvotes: 0

Views: 2634

Answers (3)

Tim Williams
Tim Williams

Reputation: 166256

You should be able to adapt this:

Sub Tester()

    Const FIND_WHAT as String = "Start"
    Const REPLACE_WITH as String = "End"

    Const REPLACE_WHICH As Long = 4 'which instance to replace?

    Dim rng As Range, i As Long

    i = 0
    Set rng = ActiveDocument.Content
    With rng.Find

        .ClearFormatting
        .Text = FIND_WHAT 

        Do While .Execute(Format:=True, MatchCase:=True, _
                           MatchWholeWord:=True)

            i = i + 1
            If i = REPLACE_WHICH Then
                'Note - "rng" is now redefined as the found range
                '  This happens every time Execute returns True
                rng.Text = REPLACE_WITH 
                Exit Do
            End If

        Loop

    End With

End Sub

Upvotes: 1

shruti1810
shruti1810

Reputation: 4037

You should use wdReplaceOne in place of wdReplaceAll.

Upvotes: 2

Simon Wray
Simon Wray

Reputation: 192

This discussion has some useful suggestions: Replace only last occurrence of match in a string in VBA. In brief, it's a case of looping through your search string from start until the first instance of the search argument is located and replacing just that.

Upvotes: 0

Related Questions