通过Excel中的VBA代码复制上下文并格式化Word文档



EXCEL中,我有一些VBA代码可以打开Word文档A并将其内容从某些页面复制到新文档。目前,我可以复制其文字。我想知道如何同时复制contextformatting。以下是我当前的代码,我感谢任何建议!

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection
'Prepare Document B
objDoc.SaveAs (Folderpath to Document B)
Set objTempWord = CreateObject("Word.Application")
Set tempDoc = objWord.Documents.Open(Folderpath to Document A)
'copy context from Document A        
With tempDoc.Application
     .Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:="2"
     .Selection.EndKey Unit:=wdStory, Extend:=wdExtend
     .Selection.Copy
End With
objSelection.TypeParagraph
objSelection.Paste
objSelection.InsertBreak Type:=wdSectionBreakNextPage
tempDoc.Close
objDoc.Application.Statusbar = False
objDoc.Save

这在这里也是如此,没有多余的额外应用对象,而无需使用选择:

Dim objWord As Word.Application
Dim objDoc As Word.Document, newDoc As Word.Document
Dim r As Word.Range, r2 As Word.Range
Set objWord = CreateObject("Word.Application") 'or Set objWord = new Word.Application
Set objDoc = objWord.Documents.Open(FolderpathToDocumentA)
Set newDoc = objWord.Documents.Add
newDoc.SaveAs FolderpathToDocumentB
Set r = objDoc.GoTo(what:=wdGoToPage, which:=wdGoToAbsolute, Name:=2)
r.End = objDoc.Range.End
'copy context from Document A
r.Copy
newDoc.Content.InsertBreak Type:=wdSectionBreakNextPage
newDoc.Range(newDoc.Content.Start, newDoc.Content.Start).Paste
newDoc.Content.InsertBefore vbCrLf
newDoc.Save
objWord.Quit

那做您需要的吗?

最新更新