在不更改VBA格式的情况下将Word文档插入到另一个Word文档中 [英] Insert word document to another word document without changing the format VBA

查看:120
本文介绍了在不更改VBA格式的情况下将Word文档插入到另一个Word文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我通过用户表单上的按钮将Word文档doc1复制到具有其格式的新Word文档中.第二,我在这个word文档的末尾(用doc1填充)插入一个新的word文档doc2(doc1和doc2得到了文本,表格和各种颜色).每次我在另一个用户表单上按下按钮以放置doc2时,都会丢失doc2的格式.

First I copy a word document doc1 to a new word document with it format via a button on a userform. Second I insert at the end of this word document (filled with doc1) a new word document doc2 (doc1 and doc2 got text and table and various colors). Each time I pressed a button on another userform to put doc2, I lose the format of 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)的格式.在线上有很多信息,但是我没有找到可能有用的信息.

I just don't want to lose the format coming from another word document (doc2). There is a lot of information online, but I didn't find the one which could be helpful.

推荐答案

将一个文档插入到另一个文档的最直接的FWIW方法是使用 InsertFile 方法,这样要插入的文档就不会出现.甚至不需要打开.

FWIW most straight-forward for inserting one document into another is to use the InsertFile method so that the document to be inserted doesn't even need to be opened.

问题中方法的问题是这样

The problem with the approach in the question is this

docTarget.Content.InsertAfter (docSource.Range.FormattedText)

必须在两侧都使用 FormattedText 属性.最好至少在目标"端使用 Range 对象,因为 InsertAfter 不能与 FormattedText 一起使用.( CollapseEnd 在问题代码中不执行任何操作,因为它没有应用于独立的 Range 对象.)

It's necessary to use the FormattedText property on both sides. It's also better to use Range objects, at least on the "target" side, since InsertAfter can't work together with FormattedText. (CollapseEnd doesn't do anything in the code in the question because it's not applied to an independent Range object.)

以下应该可以工作

Dim rngTarget as Word.Range
Set rngTarget = docTarget.Content
rngTarget.Collapse wdCollapseEnd
rngTarget.FormattedText = docSource.Content.FormattedText

这将比使用 Selection 更快,并且屏幕不会闪烁".它还将使用户的剪贴板完整无缺.

This will be faster than using Selection and the screen won't "flicker". It will also leave the user's Clipboard intact.

唯一正确的选择 Selection.Copy 是在需要显示文档属性的情况下:页眉,页脚,页面大小等.FormattedText 不会复制 section-level 属性,仅复制 Range 属性.

The only time Selection.Copy is the right thing to use is when document properties need to come across: headers, footers, page size, etc. FormattedText won't copy section-level properties, only Range properties.

这篇关于在不更改VBA格式的情况下将Word文档插入到另一个Word文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆