2017-03-05 144 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