Pages

Sunday, July 20, 2008

Creating Customized Pie Charts using Excel VBA

The following code creates a simple pie-chart using specfied data

Sub Advanced_PieChart_2003()

Dim oChts As ChartObjects '* Chart Object Collection

Dim oCht As ChartObject '* Chart Object

Dim oWS As Worksheet '* WorkSheet

On Error GoTo Err_Chart

oWS = ActiveSheet

oChts = oWS.ChartObjects

oCht = oChts.Add(100, 100, 150, 150)

oCht.Chart.ChartWizard(Source:=oWS.Range("B1", "C4"), Gallery:=XlChartType.xlPieExploded, PlotBy:=xlColumns, HasLegend:=False, Title:="Sample PieChart with Legend and Title")

oCht.Chart.ChartTitle.Position = xlChartElementPositionCustom

' Release/Dispose Objects

If Not oCht Is Nothing Then oCht = Nothing

If Not oChts Is Nothing Then oChts = Nothing

If Not oWS Is Nothing Then oWS = Nothing

Exit Sub

Err_Chart:

MsgBox(Err.Number & " - " & Err.Description)

Err.Clear()

Resume Next

End Sub

Chart postion and chart title are set programatticaly here


1 comment:

  1. Anonymous8:43 AM

    I tried your code it's showing runtime err0r 1004. I am using MS-Office 2003. Please look into this problem.

    ReplyDelete