Consulting

Results 1 to 3 of 3

Thread: .InsertAfter - insert in the same paragraph

  1. #1
    VBAX Regular
    Joined
    Jan 2018
    Posts
    58
    Location

    .InsertAfter - insert in the same paragraph

    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?
    Karol

  2. #2
    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
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    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.
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •