2016-09-20 66 views
-1

我需要編寫一個函數SaveFileWithParagraphs,它需要一個路徑,文件名和段落集合(這是從不同的word文檔中提取的)並簡單地將paragraphes寫入新的文件具有相同風格等將段落集合寫入新文檔

我有什麼至今:

Sub SaveFileWithParagraphs(path As String, name As String, paras As Collection) 
    Dim wrdApp As Word.Application 
    Dim wrdDoc As Word.Document 
    Dim i As Integer 
    Set wrdApp = CreateObject("Word.Application") 
    wrdApp.Visible = True 
    Set wrdDoc = wrdApp.Documents.Add 

    With wrdDoc 
    For Each p In paras    
     .Content.InsertAfter p.Range.Text 
    Next 
    .SaveAs (path + "\" + name) 
    .Close ' close the document 
    End With 
wrdApp.Quit ' close the Word application 
End Sub 

這樣做的問題是,我失去了段落的造型,因爲它僅複製純文本。關於如何解決這個問題的任何想法?

編輯

感謝Cominterns答案,我得到這個:

' ... 
With wrdDoc 
    For Each p In paras 
      p.Range.Copy 
      Selection.EndKey Unit:=wdStory 
      .Content.Paste 
    Next 
End With 
' ... 

其中複製了我的段落保持所有的樣式。只有一個小問題仍然存在:每當複製新段落時,它將覆蓋先前複製的段落,以便最後只有最後一段落保留在文檔中。這似乎是一個容易解決的問題,但我無法得到它的工作。任何進一步的幫助非常感謝。 :)

+0

你看過CopyFormat嗎? https://msdn.microsoft.com/en-us/library/office/ff840230.aspx – Sorceri

+0

如何從其他文檔中提取段落? – Comintern

+0

@Sorceri我不知道我在代碼中如何使用CopyFormat,但我會嘗試一下,謝謝! –

回答

1

p.Range.Text就是這樣 - 文字。如果你想保留格式,你可以複製範圍然後粘貼:

Dim target As Range 
With wrdDoc 
    For Each p In paras 
     p.Range.Copy 
     Set target = .Range 
     target.Collapse wdCollapseEnd 
     target.PasteAndFormat wdFormatOriginalFormatting 
    Next 
    .SaveAs (path + "\" + name) 
    .Close ' close the document 
End With 
+0

感謝您的回答。不幸的是,這給了我一個「期望的函數或變量」 - 錯誤在.Collapse。 –

+0

@FlorianBaierl - 那會教我鞭打一些東西,而不經過測試......查看編輯。 – Comintern

+0

完美地工作。非常感謝你! –

相關問題