Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word 2010 VBA Macro: loop to end of document

Tags:

ms-word

vba

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  
like image 765
user3689278 Avatar asked Jan 25 '26 01:01

user3689278


1 Answers

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
like image 155
user2903089 Avatar answered Jan 26 '26 20:01

user2903089



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!