繁体   English   中英

通过VBA在具有电子表格源数据的Word Doc中创建图表

[英]Creating Chart in Word Doc With Spreadsheet Source Data Via VBA

我正在尝试通过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

得到它了。 只需添加以下内容。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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