PDA

View Full Version : Excel Chart Object Name



NicoleJones
01-30-2011, 01:57 PM
Hi

I have written code that inserts and formats a chart. (below)


Sub CreateDoughnutChart()

ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$F$4:$F$14")
With ActiveChart
.ChartType = xlDoughnut
.ChartArea.Copy
.Paste
End With

With ActiveChart.SeriesCollection(1)
.Select
.ApplyDataLabels
End With
ActiveChart.SeriesCollection(2).Select
ActiveChart.ChartGroups(1).DoughnutHoleSize = 65

'Changes the label fill to clear
ActiveSheet.ChartObjects("Chart 26").Activate
ActiveChart.SeriesCollection(1).Select
With Selection.Interior
.Pattern = xlNone
End With
ActiveChart.SeriesCollection(2).Select
With Selection.Border
.Weight = xlThin
.Color = xlNone
End With
ActiveChart.Legend.Select
Selection.Position = xlBottom
ActiveChart.SetElement (msoElementChartTitleAboveChart)

End Sub

How do I write the code to find out what 'Name' the chart has just been called? So that it can be automated, at the moment I have to change the name everytime while I am testing.

Thank you for your assistance

Nicole

p45cal
01-30-2011, 06:54 PM
If it's not a different chart I think you can just delete the line:
ActiveSheet.ChartObjects("Chart 26").Activate
So you won't need to know the name.
See if this works (untested):
Sub CreateDoughnutChart()
With ActiveSheet.Shapes.AddChart
.SetSourceData Source:=Range("'Sheet1'!$F$4:$F$14")
.ChartType = xlDoughnut
.ChartArea.Copy
.Paste
.SeriesCollection(1).ApplyDataLabels
.ChartGroups(1).DoughnutHoleSize = 65
'Changes the label fill to clear
.SeriesCollection(1).Interior.Pattern = xlNone
With .SeriesCollection(2).Border
.Weight = xlThin
.Color = xlNone
End With
.Legend.Position = xlBottom
.SetElement (msoElementChartTitleAboveChart)
End With
End Sub

NicoleJones
01-30-2011, 07:50 PM
Thank you so much, I didnt think of that. It worked!

Cosmo
01-31-2011, 01:32 PM
You can set a variable to the chart as it's created, and refer to that variable to set the properties.
Sub CreateDoughnutChart()
Dim oShp As Shape
Set oShp = ActiveSheet.Shapes.AddChart

With oShp.Chart
.SetSourceData Source:=Range("'Sheet1'!$F$4:$F$14")
.ChartType = xlDoughnut
.ChartArea.Copy
.Paste

.SeriesCollection(1).ApplyDataLabels
.ChartGroups(1).DoughnutHoleSize = 65
'Changes the label fill to clear
.SeriesCollection(1).Interior.Pattern = xlNone
With .SeriesCollection(2).Border
.Weight = xlThin
.Color = xlNone
End With
.Legend.Position = xlBottom
.SetElement (msoElementChartTitleAboveChart)
End With
End Sub


I've also cleaned out a lot of your 'Select' statements - they are not needed.