[英]Using vba to copy the contents of a word document into another word document
[英]Insert word document to another word document without changing the format VBA
首先,我通过一个用户表单上的按钮将一个word文档doc1复制到一个新的word文档中。 其次,我在这个word文档的末尾(用doc1填充)插入一个新的word文档doc2(doc1和doc2得到了文本,表格和各种颜色)。 每次我在另一个用户表单上按下按钮以放置doc2时,都会丢失doc2的格式。
这是我的代码:
Dim docSource As Document
Dim docTarget As Document
Set docTarget = ActiveDocument
Set docSource = Documents.Open(strFilename)
' Add the content of docSource to docTarget
docTarget.Range.Collapse Direction:=wdCollapseEnd
docTarget.Content.InsertAfter (docSource.Range.FormattedText)
docSource.Close (0)
我只是不想丢失来自另一个Word文档(doc2)的格式。 在线上有很多信息,但是我没有找到可能有用的信息。
FWIW将一个文档插入到另一个文档中最简单的方法是使用InsertFile
方法,这样甚至不需要打开要插入的文档。
问题中方法的问题是这样
docTarget.Content.InsertAfter (docSource.Range.FormattedText)
必须在两边都使用FormattedText
属性。 最好至少在“目标”侧使用Range
对象,因为InsertAfter
不能与FormattedText
一起使用。 ( CollapseEnd
在问题代码中不执行任何操作,因为它没有应用于独立的Range
对象。)
以下应该工作
Dim rngTarget as Word.Range
Set rngTarget = docTarget.Content
rngTarget.Collapse wdCollapseEnd
rngTarget.FormattedText = docSource.Content.FormattedText
这将比使用“ Selection
更快,并且屏幕不会“闪烁”。 它还将使用户的剪贴板完整无缺。
只有在需要遇到文档属性时(例如页眉,页脚,页面大小等), Selection.Copy
才是正确的Selection.Copy
FormattedText
不会复制节级别的属性,而只会复制Range
属性。
您应该尝试使用特殊复制和粘贴:
请尝试以下操作:
Sub PasteWithFormat()
Dim docSource As Document
Dim docTarget As Document
Set docTarget = ActiveDocument
Set docSource = Documents.Open(strFileName)
docSource.Select
Selection.HomeKey Unit:=wdStory
Selection.EndKey Unit:=wdStory, Extend:=wdExtend
Selection.Copy
docTarget.Select
Selection.EndKey Unit:=wdStory
Selection.PasteAndFormat (wdPasteDefault)
docSource.Close
Set docSource = Nothing
Set docTarget = Nothing
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.