PDA

View Full Version : Stuck in a loop



mantooth29
08-04-2012, 10:06 AM
Hello

I have the following code that loops through a mail merge output document, and copies a name in the greeting line. I have watched the behavior of the macro when it executes. It seems to go back and forth over the same section indefinitely, never actually making it to the next result and eventually crashing.

I recorded the macro to make sure the selection.find command was going to the next section, so I am guessing my problem lies in how I set up the loop.


Selection.Find.ClearFormatting
Selection.Find.Text = "and Team"
With Selection.Find
.Text = "and Team"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
Selection.Find.Execute
Do While Selection.Find.Found
Selection.MoveLeft Unit:=wdCharacter, Count:=2, Extend:=wdExtend
Selection.Copy
Selection.MoveDown Unit:=wdParagraph, Count:=1
Selection.Find.Execute
Loop


Any help is much appreciated!

macropod
08-04-2012, 11:11 PM
There seems to be a slight oversight here - you're trying to copy something, but then you don't do anything with what you've copied.

Be that as it may, try something based on:
Sub Demo()
With Selection
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "and Team??"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
.Range.Copy
MsgBox .Range.Text
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
End Sub

mantooth29
08-05-2012, 07:52 AM
Man I am glad you answered! It seems like the wildcard parameters were important in making this work. Is that pretty standard for this kind of procedure?

I actually have a question from your many to one mail merge tutorial that is related to what I am trying to do. I will start a new thread for that.

Thanks!

macropod
08-05-2012, 03:18 PM
It could be done without wildcards - it's just easier that way. The alternative would be to have code that extends the found range within the loop similar to what you were trying to do.