问题
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.
Here my code:
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)
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.
回答1:
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)
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.)
The following should work
Dim rngTarget as Word.Range
Set rngTarget = docTarget.Content
rngTarget.Collapse wdCollapseEnd
rngTarget.FormattedText = docSource.Content.FormattedText
This will be faster than using Selection
and the screen won't "flicker". It will also leave the user's Clipboard intact.
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.
回答2:
You should try using copy and paste special:
Try the following:
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
来源:https://stackoverflow.com/questions/54496552/insert-word-document-to-another-word-document-without-changing-the-format-vba