![](/img/trans.png)
[英]Is there a way to use excel vba to open a word document, copy a word table, and paste it to another word document
[英]Copy table from Word and paste into another Word document
我正在尝试打开一个 Word 文档并复制其中的整个表格,然后将其粘贴到另一个已打开的文档中特定标题/书签(我已在文档中添加书签)之后。 然后最后提示用户用新粘贴的表格保存文档。
网上看到的例子是 Excel 到 Word 或 Word 到 Excel; 我需要逐字逐句。
我能够提取第一个文档(我认为它也成功复制了它——我还没有测试过),但是当它激活第二个文档时,它会停止并给出一个错误,它没有分配的对象。
调试器突出显示Set WrdRng = Active.Bookmarks("AppendixA").Range
。
Sub TEST()
'
' Declare Table Document Var as Object
Dim tb As Object
Dim bk As Bookmark
Dim WrdRng As Range
'
'
'Set up Word Application
Set tb = CreateObject("Word.Application")
tb.Visible = True
'Opens Pre-Saved Document & activates it to use
tb.Documents.Open "C:\ Desktop\Table.dotm"
tb.Activate
Selection.WholeStory
'ActiveDocument.Tables(1).Select
Selection.Font.Name = "Calibri"
Selection.Copy
'Activate Rolling Trend Report Document and Paste
Windows("TEST - Compatibility Mode").Activate
' where the error occurs and the debugger highlights
Set WrdRng = Active.Bookmarks("AppendixA").Range
'Paste to Bookmark
With WrdRng
Selection.InsertAfter
End With
'Save Completed Report to Desktop
ChangeFileOpenDirectory "C: \Desktop\"
ActiveDocument.SaveAs2 FileName:="TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
'
'
'
End Sub
您的代码失败,因为Set WrdRng = Active.Bookmarks("AppendixA").Range
应该是Set WrdRng = ActiveDocument.Bookmarks("AppendixA").Range
但是,您的代码写得不好,在其他地方也会失败,并且会创建一个额外的 Word 实例。
下面的代码是从 Word 运行的
Sub TEST()
'store a pointer to the document you wnat to insert table into
'assumed to be currently active document
Dim targetDoc As Document
Set targetDoc = ActiveDocument
'Open Pre-Saved Document
Dim tblDoc As Document
Set tblDoc = Documents.Open("C:\ Desktop\Table.dotm")
Dim source As Range
Set source = tblDoc.Content
'exclude the paragraph that comes after the table
source.MoveEnd Unit:=wdCharacter, Count:=-1
source.Font.Name = "Calibri"
Dim appxA As Range
Set appxA = targetDoc.Bookmarks("AppendixA").Range
appxA.Collapse wdCollapseEnd
'transfer the text and close the source document
appxA.FormattedText = source.FormattedText
tblDoc.Close wdDoNotSaveChanges
'it is necessary to pass the full file path to the SaveAs command
ActiveDocument.SaveAs2 FileName:="C: \Desktop\TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.