Replae ^p in Selected Text in VBA

T

Tim of Calgary

I am copying multiple blocks of text from a raw file to a Word file and have
to reformat them as I go. The macro consists of a number of iterations of
F&R, and is designed to run over a selection (believe me, this is easier than
grepping the source docs).

When the macro hits this combo:

find = "^p"
replace with = " "

(to remove para breaks; another part reinserts them in the correct places).

The macro ignores the direction to stop at end of selection and instead
wipes all carriage returns to the end of the document, and by the way applies
the style of the last paragraph of the doc to everything from the selection
start on.

Any thoughts on how to fix this? The F&R works fine if done manually, just
not in a macro.
 
J

Jay Freedman

Hi Tim,

Yeah, VBA's .Find doesn't work the same way as the UI Find regarding
limiting to the selected text. You need to do something like this to check
that each found item is within the original selection before replacing it:

Sub demo()
Dim oRg As Range
Dim oRgOrig As Range
Set oRg = Selection.Range
Set oRgOrig = Selection.Range
With oRg.Find
.ClearFormatting
.Text = "^p"
.MatchWildcards = False
.Wrap = wdFindStop
Do While .Execute
If oRg.InRange(oRgOrig) Then
oRg.Text = " "
oRg.Collapse wdCollapseEnd
Else
Exit Do
End If
Loop
End With
End Sub
--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
T

Tony Jollans

If you want to replace all paragraph marks within a Range you don't need a
loop just use

(Range).Find.Execute Replace:=wdReplaceAll
 
J

Jay Freedman

What was that about forests and trees? :)

Tony said:
If you want to replace all paragraph marks within a Range you don't
need a loop just use

(Range).Find.Execute Replace:=wdReplaceAll
 
T

Tim of Calgary

I tried the macro last night and it worked fine; I didn't see the other
solution until this morning. My plan here is to be both clever and lazy, so I
will try the other tonight.

Thanks for the help.

Tim.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top