Word 2010 VBA Macro: loop to end of document

16,983

Change you code to this, note the use of wdFindStop.

Selection.Find.ClearFormatting
     With Selection.Find
    .Text = "Quantity:"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = True
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With

do while Selection.Find.Execute = true
   Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph  
loop

If you have the type of documents this can fail on you can use the Selection.Start by replacing the loop like this:

Dim lastPos As Long
lastPos = -1
Do While Selection.Find.Execute = True
    If lastPos > Selection.Start Then Exit Do
    Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph
Loop
Share:
16,983
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have recorded a simple macro to find the word "Quantity", go to the end of that line and insert a carriage return. I need to repeat it to the end of the document and quit, or else I'll have an infinite loop.

    The code:

         Selection.Find.ClearFormatting
         With Selection.Find
        .Text = "Quantity:"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute
    Selection.EndKey Unit:=wdLine
    Selection.TypeParagraph