Log in

View Full Version : Insert text then run multiple FIND/REPLACEs on the newly inserted text



o1sowise
05-28-2019, 01:26 PM
HELP!

I can insert the text, using the correct STYLE, indent, etc. (code not included), but I cannot seem to get the FIND/REPLACE logic below to work on the newly inserted text only. My SourceText Array is loaded in order of what I expect to find. e.g. run thru the list until it finds a match, replace it, then stop. The code below changes none of the newly inserted test - however it sometimes changes text later on in the doc, way past the newly inserted code. :crying:


For i = LBound(SourceText) To UBound(SourceText)
Selection.Find.ClearFormatting
Selection.Find.Text = SourceText(i)

Selection.Find.Replacement.Text = TargetText(i)
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = vbYellow

Selection.Find.MatchCase = True
Selection.Find.MatchWholeWord = True
Selection.Find.MatchWildcards = False
Selection.Find.MatchSoundsLike = False
Selection.Find.MatchAllWordForms = False
Selection.Find.Format = True
Selection.Find.Forward = True
Selection.Find.Wrap = wdFindStop ' wdFindContinue

Selection.Find.Execute Replace:=wdReplaceOnce
If Selection.Find.Found = True Then
Debug.Print "Found"
Selection.Find.Replacement.Font.Bold = True
Exit For
End If
Next i

gmayor
05-29-2019, 12:37 AM
It all revolves around 'Selection'. Your code gives no indication of what the Selection is or how you have inserted the text into the document and indeed whether that inserted text is selected in order for it to be the selection.
You would be better working with ranges rather than the selection object and reset the start range for each iteration of the loop.

o1sowise
05-29-2019, 05:44 AM
THANK YOU, Graham! :idea:
That's the logic piece of the puzzle I've been missing!!!

It now works like a charm!!!!!
Thanks again!

o1sowise
05-29-2019, 01:48 PM
One final question:

My code now inserts the text and changes certain phrases, just like I need.
My only remaining issue is that the new text is indented differently than the text above it.
How do I query the text above and make the indent of the new text match it?

o1sowise
05-30-2019, 06:41 AM
I've moved this new question to a new post (http://www.vbaexpress.com/forum/showthread.php?65244-Can-I-Query-Mirror-INDENT&p=391142#post391142). Please answer there (http://www.vbaexpress.com/forum/showthread.php?65244-Can-I-Query-Mirror-INDENT&p=391142#post391142).