How to merge word documents in vba

Written by jaime avelar
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to merge word documents in vba
In a few steps you can merge Word documents using VBA. (Icone di cartelle image by persefone from Fotolia.com)

Merging Microsoft Word documents using Visual Basic for Applications (VBA) can save you time when working with different documents. Microsoft Word is a word processing application that comes with the Microsoft Office (MS Office) suite. VBA is used when you need to automate routine tasks to create a result. VBA can be used in any of the MS Office applications. You can use a code to copy text from multiple documents into one.

Skill level:
Easy

Other People Are Reading

Instructions

  1. 1

    Start Microsoft Word 2007. Select the "Developer" tab and click "Visual Basic." Right-click "Microsoft Word Objects," click "Insert" and select "Module."

  2. 2

    Type the following to create a new sub:

    Sub mergeTwoDocs()

    Press "Enter."

  3. 3

    Type the following to create variables used for storing data:

    Dim wDoc As Word.Document

    Dim paragraph Text As String

    Dim paragraph Range As Word.Range

    Dim paragraph Count As Long

  4. 4

    Type the following to define your "wordApplication" variable:

    Set word Application = CreateObject("Word.Application")

    Type the following to open the "first" document to merge:

    Set wDoc = wordApplication.Documents.Open("C:\This is text from the first document.doc")

    Type the following to call the "readDocument" sub and send the "first" document object as a parameter:

    Call read Document(wDoc)

  5. 5

    Type the following to open the "second" document to merge:

    Set wDoc = wordApplication.Documents.Open("C:\This is text from the second document.doc")

    Type the following to call the "readDocument" sub and send the "second" document object as a parameter:

    Call read Document(wDoc)

  6. 6

    Type the following to create the "readDocument" sub that will read any word document object passed in and add the contents to the current document:

    Private Sub read Document(wrdDoc As Object)

    With wrdDoc
    
        For paragraph Count = 1 To .Paragraphs.Count
    
            Set paragraph Range = .Range(Start:=.Paragraphs(paragraphCount).Range.Start, _
    
                End:=.Paragraphs(paragraphCount).Range.End)
    
            paragraph Text = paragraphRange.Text
    
    
    
            Selection.TypeText Text:=paragraph Text
    
            Selection.TypeParagraph
    
    
    
        Next paragraph Count
    
        .Close
    
    End With
    

    End Sub

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.