2017-03-05 145 views
1

我正在编写一个程序,该程序应该将几个word文档合并成一个文档,以保持每个文档的格式。之后,网络上的一些研究,写的是这样运作的一个版本,它是这样的:合并VB文档中保存格式的word文档

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 

我收到以下错误:

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

指的是以下行:

destDoc.Activate() 

我读过这应该是因为代码使用一个不合格的方法对已结束的Office实例,但我无法理解如何修复它

+0

粘贴 – Slai

回答

1

我不知道如何在VB.NET中做到这一点,但下面的VBA代码将所有的Word文档合并成一个合并的Word文档。

追加多个Word文档到一个单一的Word文档

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 
+0

我看到这个代码,但也许是因为我不能够把它翻译到VB .NET之前不要关闭源文件,但它不起作用 –

+0

在MS Word中运行!打开Word,点击Alt + F11,然后将该代码粘贴到打开的窗口中。当然,您将需要更改所有Word文档所在的路径...... – ryguy72