提问人:Michael 提问时间:10/24/2023 更新时间:10/24/2023 访问量:26
将图表和表格从 excel 粘贴到现有 word 文档中,粘贴到文档的特定部分
Paste Chart and Table from excel to existing word document into a specific part of the document
问:
我正在使用下面的VBA代码将表格和图表从excel电子表格复制并粘贴到模板word文档中。
当我运行下面的宏时,图表和表格将粘贴在文档的顶部。有谁知道选择图表和表格的粘贴位置的方法?
此外,如果有一种方法可以格式化表格,使其自动适合文档,那就太好了。
Sub ExportChartandTableToExistingTemplatePara()
'Declare Word Object Variables
Dim WrdApp As Word.Application
Dim WrdDoc As Word.Document
Dim WrdTbl As Word.Table
Dim wordTable As Object
'Declare Excel Object Variables
Dim Chrt As ChartObject
Dim ExcListObj As ListObject
'Open Template
Dim oAPP As Object
Set oAPP = CreateObject(Class:="Word.Application")
oAPP.Visible = True
oAPP.Documents.Open Filename:="C:\Users\michael.okeefe\Documents\PurchaseUpdateReportExampleTest.docx"
'Create a Reference to the chart I want to Export
Set Chrt = ActiveSheet.ChartObjects(1)
Chrt.Chart.ChartArea.Copy
'Paste into Word Document
With oAPP.Selection
.PasteSpecial Link:=True, DataType:=wdPasteOLEObject
End With
'Create a Reference to List Object to Copy
Set ExcListObj = ActiveSheet.ListObjects(1)
ExcListObj.Range.Copy
'Paste into Word Document
With oAPP.Selection
.PasteExcelTable LinkedToExcel:=False, WordFormatting:=False, RTF:=False
End With
End Sub
我希望表格显示在第一段之后,图表显示在后面的页面上。
答:
0赞
Timothy Rylatt
10/24/2023
#1
你的代码是一团糟。在例程的顶部声明所需的对象,不要使用其中任何一个对象,然后声明 .oAPP As Object
我已使您的代码保持一致,并向您展示了如何将表粘贴到已知位置。您需要确定图表需要去哪里,并为此使用类似的代码。
Sub ExportChartandTableToExistingTemplatePara()
'Declare Word Object Variables
Dim WrdApp As Word.Application
Dim WrdDoc As Word.Document
Dim WrdTbl As Word.Table
'Declare Excel Object Variables
Dim Chrt As ChartObject
Dim ExcListObj As ListObject
'Open Template
Set WrdApp = New Word.Application
WrdApp.Visible = True
Set WrdDoc = WrdApp.Documents.Open(Filename:="C:\Users\michael.okeefe\Documents\PurchaseUpdateReportExampleTest.docx")
'Create a Reference to the chart I want to Export
Set Chrt = ActiveSheet.ChartObjects(1)
Chrt.Chart.ChartArea.Copy
'Paste into Word Document
'you need to identify exactly where this needs to be pasted
'Create a Reference to List Object to Copy
Set ExcListObj = ActiveSheet.ListObjects(1)
ExcListObj.Range.Copy
'Paste into Word Document
WrdDoc.Paragraphs(2).Range.PasteExcelTable LinkedToExcel:=False, WordFormatting:=False, RTF:=False
End Sub
评论
0赞
Michael
10/26/2023
嗨,蒂莫西,非常感谢您在这方面的帮助。我同意我的代码是一团糟,从多个来源拼凑在一起。如果我将图表粘贴到第 5 段中,我会在代码中添加什么?
0赞
Timothy Rylatt
10/26/2023
@Michael - 非此即彼WrdDoc.Paragraphs(5).Range.PasteAndFormat wdChartLinked
WrdDoc.Paragraphs(2).Range.PasteSpecial Link:=True, DataType:=wdPasteOLEObject
评论