[英]Creating Chart in Word Doc With Spreadsheet Source Data Via VBA
I am trying to modify a Word doc template by adding a bar graph via VBA. 我正在尝试通过VBA添加条形图来修改Word文档模板。 The source data is from an existing Excel spreadsheet. 源数据来自现有的Excel电子表格。 I am doing this in Excel's VBE. 我正在Excel的VBE中执行此操作。 However, this code merely creates a new chart on a spreadsheet. 但是,此代码仅在电子表格上创建一个新图表。 It does not add it to my Word doc. 它不会将其添加到我的Word文档中。 How can I incorporate the chart straight into the doc? 如何将图表直接纳入文档?
Option Explicit
Sub UpdateChartData()
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim cht As Chart
Dim ws1 As Worksheet
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add("C:\...\chart_test.docx")
Set cht = Charts.Add
'' Worksheet of the source data.
Set ws1 = ActiveWorkbook.Sheets("Sheet1")
'' Go to the Word bookmark where the chart will be inserted.
wdDoc.GoTo what:=-1, Name:="insert_chart"
With cht
'' Source data range.
.SetSourceData Source:=ws1.Range("A2:C12")
.ChartType = xlColumnClustered
End With
With wdApp
.Visible = True
.Activate
End With
End Sub
Got it. 得到它了。 Just add the following. 只需添加以下内容。
cht.CopyPicture
wdDoc.Bookmarks("insert_chart").Range.Paste
cht.Copy
will not display the chart on the doc. cht.Copy
将不会在文档上显示图表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.