2014-08-29 203 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 

我希望这会有所帮助(你或某人......)。