Question

I am trying to use a macro to find and replace some text in a Word 2007 document. I want to autoincrement a number in the replacement text every time the text is found.

Text before:

The quick brown (??) fox jumps over (??) the (??) lazy dog

Desired text after:

The quick brown (1) fox jumps over (2) the (3) lazy dog

For some reason my code only replaces the first instance:

Sub SetRequirements()
    Dim myNumber As Integer
    myNumber = 1

    With ActiveDocument.Content.Find
        .ClearFormatting
        .Text = "(??)"
        Do While .Execute( _
            Replace:=wdReplaceOne, _
            ReplaceWith:="(" & myNumber & ")", _
            Forward:=True) = True

            myNumber = myNumber + 1

        Loop
    End With
End Sub

Help?

Was it helpful?

Solution

Sub SetRequirements()

Const S_FIND As String = "(??)"
Dim myNumber As Integer

    myNumber = 1

    Do While InStr(ActiveDocument.Content, S_FIND) > 0
        With ActiveDocument.Content.Find
            .ClearFormatting
            .Text = S_FIND
            .Execute Replace:=wdReplaceOne, ReplaceWith:="(" & myNumber & ")", _
                     Forward:=True
        End With
        myNumber = myNumber + 1
    Loop

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top