PDA

View Full Version : .InsertAfter - insert in the same paragraph



dagerr
12-17-2018, 09:46 AM
Hi, the following code add text after paragraph but on begin of next paragraph e.g.:


Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
</Body>



Sub test_xml()


Dim lPar As Paragraph
For Each lPar In ActiveDocument.Range.Paragraphs

If lPar.Range.Font.Bold = True _
And lPar.Range.Font.Size = 9 _
And Len(lPar.Range) > 2 Then


lPar.Range.InsertAfter "</Body>"
End If
Next
End Sub


I want to add text after paragraph end but on the same paragraph:
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </Body>


I figured out that part of code below work properly but not every time:

lPar.Range.Characters.last.InsertBefore "</Body>"

instead of:

lPar.Range.InsertAfter "</Body>"




Is there straight syntax to solve that problem?

gmayor
12-18-2018, 06:31 AM
A paragraph range includes the paragraph end character so reduce the range to eliminate that e.g. as follows. It will work provided the paragraphs meet the criteria you have set.


Sub test_xml()
Dim lPar As Paragraph
Dim oRng As Range
For Each lPar In ActiveDocument.Range.Paragraphs
Set oRng = lPar.Range
oRng.End = oRng.End - 1
If oRng.Font.Bold = True _
And oRng.Font.Size = 9 _
And Len(oRng) > 1 Then
oRng.InsertAfter "</Body>"
End If
Next lPar
Set lPar = Nothing
Set oRng = Nothing
End Sub

macropod
12-18-2018, 08:29 PM
Or a wildcard Find/Replace, where:
Find = ([!^13]@)(^13)
Replace = \1</Body>\2
and the font attributes are included as Find parameters. A macro so coded is likely to be much faster than one that loops through all paras.