简体   繁体   中英

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. The source data is from an existing Excel spreadsheet. I am doing this in Excel's VBE. However, this code merely creates a new chart on a spreadsheet. It does not add it to my Word doc. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM