【问题标题】:Insert word document to another word document without changing the format VBA将word文档插入另一个word文档而不更改格式VBA
【发布时间】:2019-02-03 15:56:31
【问题描述】:

首先,我通过用户窗体上的按钮将一个 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


    【解决方案1】:

    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 属性。

    【讨论】:

    • 太好了。它工作得很好。我试图用 docTargetContent 替换 rngTarget 以简化为 2 行而不是 4 行,但它没有用。我不确定为什么尽管你的解释很好,还是因为 rngTarget 需要是一个独立的 Range 对象?。
    • @JLuc01 它需要是它自己的Range 对象。否则,您仍在引用文档的全部内容。
    【解决方案2】:

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

    尝试以下方法:

        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
    
    

    【讨论】:

    • 谢谢。它工作得很好,我理解逻辑。我很惊讶你在我之前的问题/帖子中使用选择/选择,不建议使用它,显然不是一个好的编码习惯。
    • 是的,不是,而是因为你正在做的事情又快又容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多