Insert Chart in Word Document using VBA

Insert Chart in Word Document using VBA

Chart:

Charts are very informative objects within a document which helps representing data into graphical form. Microsoft offers Chart Object by which developer can manipulate charts. Chart can heave two forms:

  1. Embedded Chart: Where source and Chart both clubbed to gather.
  2. Separate Chart: Where source kept in separate source and Chart separate.

Understand Charts Object:

Charts is a collection which contains Chart object for each chart sheet. An index (integer) can be used to iterate specific chart from charts collection.

Let’s take an example, how to create chart using VBA (Macro) code in a Word document:

Sub Insert_Chart()
    Dim objShape As InlineShape
        
    ' The Shape object reference contains the chart.
    Set objShape = ActiveDocument.InlineShapes.AddChart(XlChartType.xlColumnStacked100)
    
    'set the source data for the chart to the range A1:C3.
    If objShape.HasChart Then
        objShape.Chart.SetSourceData Source:="'Sheet1'!$A$1:$C$3"
    End If
End Sub

Let’s take a look what happens when you run above code:

A chart gets inserted in selected range, but to be noticed, there is a quick popup which launches the excel workbook by pre-populated data in a sheet as shown below:

Now you can make changes in the given excel file and go back in word document, the charts gets changed as per changes made into the source.

To verify, I have changed the data into source sheet as shown below:

Now check the output:

Chart Title:

Sub chartModification()
    'Change chart title
    ActiveDocument.InlineShapes(1).Chart.HasTitle = True
    ActiveDocument.InlineShapes(1).Chart.ChartTitle.Text = "My Chart"
End Sub

Please leave your valuable comments

Leave a Reply

Your email address will not be published.