Pages

Sunday, July 20, 2008

Adding a Pie Chart to a Sheet using Excel VBA

Creating Excel Pie Chart using Excel VBA


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


Sub Add_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(oWS.Range("B1", "C4"), XlChartType.xlPieExploded)




' 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




The code uses Chartwizard method to modify the properties of the given chart. You can use this method to quickly format a chart without setting all the individual properties. This method is noninteractive, and it changes only the specified properties.


See also:


How to add Format Conditions using Excel VBA


How to Search a specific Colored Text (Range) using Excel VBA



No comments:

Post a Comment