none
VBA macro( for Word) to insert text in the begining of first paragraph and end of last paragraph RRS feed

  • Question

  • I have a word document in which i need to insert a text in the begining of first paragraph and end of last paragraph.

    My code is inserting text in the begining of first paragraph and end of same paragraph.And the bullets and numbering should also be included.Could some one please help me out in solving this issue.

    Set TargetStyle = ActiveDocument.Styles(Heading)
            
            With Selection.Find
                .Text = ""
                .ClearFormatting
                .Style = TargetStyle
                .Forward = True
                .Wrap = wdFindStop
                .Format = True
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute
           
           If .Found Then
            Dim drange As Range
            Selection.HomeKey wdStory
            Selection.Find.Style = Heading
            With Selection.Find
                Do While .Execute(findText:="", Forward:=True, _
                    MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=False) = True
                    Set drange = Selection.Range
                    
                    If drange.Information(wdWithInTable) Then
                        Selection.Collapse wdCollapseEnd
                    ElseIf (drange.ListFormat.ListType = WdListType.wdListBullet) Or (drange.ListFormat.ListType = WdListType.wdListSimpleNumbering) Then
                        Selection.Collapse wdCollapseEnd
                    Else
                        drange.InsertBefore "<" & Req & ">"
                        drange.End = drange.End - 1
                        drange.InsertAfter "<" & "/" & Req & ">"
                        Selection.Collapse wdCollapseEnd
                    End If
                Loop

    Thanks in Advace!           
            End With
            
            End If

       End With

    Tuesday, January 3, 2017 12:01 PM

All replies

  • If you want to add text before the first paragraph and after the last paragraph, the code required is much more straightforward.

    ActiveDocument.Range.InsertBefore "Text to insert before "
    ActiveDocument.Range.InsertAfter "Text to insert after."

    Having briefly looked at your code, it is both incomplete and unclear what it is supposed to be doing. What, for example, does 'Req' refer to?

    The nature of the document is unknown. There is also a reference to a table.How does this fit into the picture?

    If you only provide a fraction of the required information, you are not going to get the answer you want.




    Graham Mayor - Word MVP
    www.gmayor.com

    Tuesday, January 3, 2017 1:00 PM
  • Firstly thanks for your valuable inputs.And sorry for providing incomplete data.

    According to my requirement:

    1.I need to identify the style in the word document.

    2.Based on style ,I need to insert  "<Requirement> " tag in the beginning of the first and end of the last paragraph.

    The code which you shared inserts the tag in the beginning and end of same paragraph.

    3.If any  tables between the paragraph then tags should not be inserted inside the table data but table should be included between the tags.Same for Image aswel.Please find the below text ,i need ti insert like this.

    <Requirement>To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other. For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries.

    Col1

    Col2

    Col3

     Insert

     

     

     

     

     

    Save time in Word with new buttons that show up where you need them. To change the way a picture fits in your document, click it and a button for layout options appears next to it. When you work on a table, click where you want to add a row or a column, and then click the plus sign. </Requirement>

     4.And in Vba every bullets are also considered as paragraph.But i want to insert tag as shown below

     Expected:

    <Requirement>Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.

    • To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other.
    • For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries.

    Save time in Word with new buttons that show up where you need them. To change the way a picture fits in your document, click it and a button for layout options appears next to it. When you work on a table, click where you want to add a row or a column, and then click the plus sign. </Requirement>

    Actually my code is working as below which is not expected:

    <Requirement>Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document.</Requirement>

    • <Requirement>For example, you can add a matching cover page, header, and sidebar. </Requirement>
    • <Requirement>Click Insert and then choose the egalleries.</Requirement>

    <Requirement>Save time in Word with new buttons that show up where you need them. To change the way a picture fits in your document, click it and a button for layout options appears next to it. When you work on a table, click where you want to add a row or a column, and then click the plus sign. </Requirement>

    Please find the complete code:

    '--------------------------------------------------------------------------------------
    '----Macro to Insert the Requirement and Comment tags in Requirement word doc------------------
    '--------------------------------------------------------------------------------------




    '----------Global variables declaration---------

    Public Req1 As String
    Public Req2 As String
    Public com1 As String
    Public com2 As String


    Sub HeadingStyle()

    '----------Global variables intialization---------
            Req1 = "Requirement"
            Req2 = "Requirement Phase 2"
            com1 = "Comment"
            com2 = "Comment Phase 2"
            
            
    '----------Call function to insert <<START>> and <<END>> tags---------
            Call DetectUMH1Style("Heading 4", Req1)
            Call DetectUMH1Style("Heading 2", Req2)
            Call DetectUMH1Style("Heading 3", com1)

    End Sub

     
    Public Sub DetectUMH1Style(Heading As String, Req)

             Dim TargetStyle As Style
    '----------Select the current page---------
             ActiveDocument.Bookmarks("\page").Range.Select
        
          
    '----------Search for target style----------
             Set TargetStyle = ActiveDocument.Styles(Heading)
            
            With Selection.Find
                .Text = ""
                .ClearFormatting
                .Style = TargetStyle
                .Forward = True
                .Wrap = wdFindStop
                .Format = True
                .MatchCase = False
                .MatchWholeWord = False
                .MatchWildcards = False
                .MatchSoundsLike = False
                .MatchAllWordForms = False
                .Execute
           
           If .Found Then
            Dim drange As Range
            Selection.HomeKey wdStory
            Selection.Find.Style = Heading
            With Selection.Find
                Do While .Execute(findText:="", Forward:=True, _
                    MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=False) = True
                    Set drange = Selection.Range
                    
                    If drange.Information(wdWithInTable) Then
                        Selection.Collapse wdCollapseEnd
                    ElseIf (drange.ListFormat.ListType = WdListType.wdListBullet) Or (drange.ListFormat.ListType = WdListType.wdListSimpleNumbering) Then
                        Selection.Collapse wdCollapseEnd
                    Else
                        drange.InsertBefore "<" & Req & ">"
                        drange.End = drange.End - 1
                        drange.InsertAfter "<" & "/" & Req & ">"
                        Selection.Collapse wdCollapseEnd
                    End If
                Loop
                
            End With
            
            End If

       End With
        
    End Sub



    Thanks in advance.Please help me out.



    Wednesday, January 4, 2017 5:03 AM
  • I don't think what you are asking for is possible, and certainly not without seeing the document.

    Your code looks for particular paragraph styles to add the texts to, but your example text is not in document format, so it is not possible to see what styles are used.

    Adding a text to the start of a particular paragraph is easy enough. It is the determination of where to add the ending texts that presents the problem. The code I posted adds the text at the beginning of the first paragraph and the end of the last paragraph, which was what you asked for, but obviously not what you required.

    I see that you have used the method to add the code to the start and end of the paragraph range. That's fine if the paragraph end is the end of the range to be processed, but it  may not necessarily be, and there may be other paragraphs that have the same format that may or may not be required to be included in the ranges to be processed.

    The problem as you have identified concerns the presence of a table in the text to be processed, which clearly is in a different paragraph. Similarly you have bulleted texts which, as you acknowledge, are also separate paragraphs and without the document it is not possible to see how those bulleted paragraphs are created. Thus locating the end of the required range is variable and difficult to determine.


    Graham Mayor - Word MVP
    www.gmayor.com

    Wednesday, January 4, 2017 8:14 AM
  • Thanks for your time.

    Actually here i don't find any option to attach the word document.Please let me know if any way to do this.

    So that i could share my document and script aswell.

    Thanks!

    Wednesday, January 4, 2017 8:26 AM
  • Could you please reply..is their any way to share my word document so that it would be easy to find the solution.

    Thanks for your time!

    Thursday, January 5, 2017 10:14 AM
  • The solution may not be easy (or even possible) even with the document. However can you post the file somewhere e.g. dropbox or onedrive and post the link to the file?


    Graham Mayor - Word MVP
    www.gmayor.com

    Thursday, January 5, 2017 12:37 PM