插入Word文档到另一个Word文档,而不改变格式VBA

问题描述 投票:2回答:2

首先,我通过一个按钮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)未来的格式。有很多的网上资料,但我没有找到一个可能是有帮助的。

vba ms-word format
2个回答
4
投票

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就是用正确的做法是,当文件属性需要遇到:页眉,页脚,页面大小等FormattedText不会复制科级特性,只有Range性能。


0
投票

你应该尝试使用复制和粘贴特殊:

尝试以下方法:

    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

© www.soinside.com 2019 - 2024. All rights reserved.