none
VBA Macro Replace gets out of selection in word2010 RRS feed

  • Question

  • I want to replace something only in seleted paragraphs, so I selected  some sentences first and then recorded replacing operations. When I run the recorded macro on a new selection, it gets out of the selection and replaces all the text ranging from selected part to the end of the document. but it works fine with word2003, so it is a bug of word2010?

    --------CODE--------------------

     Sub myReplace()

        Selection.Find.ClearFormatting

        Selection.Find.Font.Color = wdColorAutomatic

        Selection.Find.Replacement.ClearFormatting

        Selection.Find.Replacement.Font.Color = wdColorRed

        With Selection.Find

            .Text = "is"

            .Replacement.Text = "was"

            .Forward = True

            .Wrap = wdFindAsk

            .Format = True

            .MatchCase = False

            .MatchWholeWord = False

            .MatchByte = True

            .MatchWildcards = False

            .MatchSoundsLike = False

            .MatchAllWordForms = False

        End With

        Selection.Find.Execute Replace:=wdReplaceAll

    End Sub

    Wednesday, December 29, 2010 4:34 AM

Answers

  • Hi stratodozer,

    Except for the ' .Wrap = wdFindAsk', there isn't anything I can see that might allow the process to continue beyond the selection. Try:

    Sub myReplace()
        With Selection.Find
            .ClearFormatting
            .Font.Color = wdColorAutomatic
            .Text = "is"
            With .Replacement
                .Text = "was"
                .ClearFormatting
                .Font.Color = wdColorRed
            End With
            .Forward = True
            .Wrap = wdFindStop
            .Format = True
            .MatchCase = False
            .MatchWholeWord = False
            .MatchByte = True
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            .Execute Replace:=wdReplaceAll
        End With
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]
    • Marked as answer by Bessie Zhao Wednesday, January 5, 2011 10:36 AM
    Wednesday, December 29, 2010 5:43 AM