2014-08-29 60 views
1

任何人都知道如何在不使用剪貼板的情況下將文本從一個文檔轉移到另一個文檔,但是保持文本中的所有格式(如粗體和斜體)?Word VBA使用替代剪貼板

下面是我現在的做法(這些行之間有很多代碼可以打開目錄中的文檔,但我現在忽略它們,因此我可以切入點):

Dim rng1, rng2, rngFound as Range 
Dim FSO as Scripting.FileSystemObject 

For Each File1 in FSO.GetFolder(Directory).Files 

'...Open first Document and get cursor to Point A to mark the start of the text 
Documents.Open(File1.Path) 
Set rng1 = Selection.Range 

'...Move cursor to point B to mark the end of the text 
Set rng2 = Selection.Range 

'...Combine the 2 points and capture everything in between into Clipboard 
Set rngFound = (rng1.Start, rng2.Start) 
rngFound.Copy 

ActiveDocument.Close 

'...Open up second Document and paste it in 
Documents.Open(File2.Path) 
Selection.PasteAndFormat (wdFormatSurroundingFormattingWithEmphasis) 

ActiveDocument.Save 
ActiveDocument.Close 

Next 

用做這種方式的問題在於,雖然這是運行我不能使用剪貼板(這個循環在數百頁的文件的目錄,以便需要一段時間)。

我很想找到這樣做沒有剪貼板的方式,但在保持格式從一個文檔到下一個(重要)的方式。#

希望是有道理的,謝謝提前:)

+0

查看Range對象的formattedtext成員。 – 2014-09-02 06:00:50

回答

2

這是一個使用臨時文件和InsertFile的解決方案。

將路徑替換爲Pgr以獲取您的計算機上實際存在的某個文件夾。

這只是一個概念證明。它將作爲源文檔打開"C:\Users\Pgr\AppData\Local\Temp\doc1.docx",僅將其作爲第二段,將其作爲臨時文件保存,然後返回到目標文檔(這是此宏所在的位置),並使用InsertFile將內容放到那裏。

Sub CopyThroughTempFile() 

    Set targetdoc = ActiveDocument 
    Set sourceDoc = Documents.Open("C:\Users\Pgr\AppData\Local\Temp\doc1.docx") 
    Set rng2copy = sourceDoc.Paragraphs(2) 

    rng2copy.Range.Copy 
    sourceDoc.Range.Paste 'pastes replacing everything in the file 
    sourceDoc.SaveAs ("C:\Users\Pgr\AppData\Local\Temp\temp.docx") 


    targetdoc.Activate 
    Selection.InsertFile ("C:\Users\Pgr\AppData\Local\Temp\temp.docx") 

End Sub 

我希望這會有所幫助(你或某人......)。