Merging word documents keeping format in VB NET

1

I am writing a program that is supposed to merge several word documents into one keeping the formatting of each document. After some research on the web wrote a version that is supposed to work, which is the following:

Public Sub processmodulestest(ByVal id As Integer)
    Dim oMissing = System.Reflection.Missing.Value
    Dim oFalse = False
    Dim oTrue = True
    Dim fileDirectory = "C:\<file-path>\MOD-TEST\"

    Dim wrdApp As New Word.Application
    Dim destDoc As Word.Document 'destination doc
    Dim docfile As Word.Document 'tmp doc to paste
    destDoc = wrdApp.Documents.Add

    'docNew.PageSetup.TopMargin = wrdApp.InchesToPoints(1.0F)
    'docNew.PageSetup.BottomMargin = wrdApp.InchesToPoints(0.0F)
    Dim wordFiles() As String = Directory.GetFiles(fileDirectory, "*.doc")

    wrdApp.Options.Pagination = False
    wrdApp.ActiveWindow.View.ShowAll = True

    For Each el As String In wordFiles
        docfile = wrdApp.Documents.Open(el, False, False)
        wrdApp.Selection.WholeStory()
        wrdApp.Selection.Copy()
        wrdApp.ActiveWindow.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
        destDoc.Activate()
        wrdApp.Selection.PasteAndFormat(Word.WdRecoveryType.wdFormatOriginalFormatting)
        wrdApp.Selection.InsertBreak(Word.WdBreakType.wdPageBreak)
    Next

    wrdApp.Visible = True
End Sub

I get the following Error:

An unhandled exception of type'System.Runtime.InteropServices.COMException' 
HRESULT: 0x80010108 (RPC_E_DISCONNECTED)) The object invoked has disconnected from its clients.

referring to the following line:

destDoc.Activate()

I read that this should be because the code uses an unqualified method on an Office instance that has been ended, but i can't understand how to fix it

vb.net
ms-word
ms-office

1 Answer

1

I'm not sure how to do it in VB.NET, but the VBA code below will merge all Word documents into one single consolidated Word document.

Appending multiple Word docs into a single Word doc

Sub Foo()
Dim i As Long
Dim MyName As String, MyPath As String
Application.ScreenUpdating = False
Documents.Add

MyPath = "C:\Documents and Settings\Excel\Desktop\Word Files\" ' <= change this as necessary

MyName = Dir$(MyPath & "*.doc") ' not *.* if you just want doc files

Do While MyName <> ""
If InStr(MyName, "~") = 0 Then
Selection.InsertFile _
FileName:="""" & MyPath & MyName & """", _
ConfirmConversions:=False, Link:=False, _
Attachment:=False
Selection.InsertBreak Type:=wdPageBreak
End If

MyName = Dir ' gets the next doc file in the directory
Loop

End Sub
answered on Stack Overflow Mar 15, 2017 by ASH

User contributions licensed under CC BY-SA 3.0