使用电子表格源数据通过VBA在Word Doc中创建图表

时间:2016-05-02 21:00:57

标签: vba excel-2010

我正在尝试通过VBA添加条形图来修改Word文档模板。源数据来自现有的Excel电子表格。我在Excel的VBE中这样做。但是,此代码仅在电子表格上创建新图表。它不会将其添加到我的Word文档中。如何将图表直接合并到文档中?

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

1 个答案:

答案 0 :(得分:0)

知道了。只需添加以下内容即可。

cht.CopyPicture
wdDoc.Bookmarks("insert_chart").Range.Paste

cht.Copy不会在文档上显示图表。