在Excel VBA中编辑和命名新添加的图表

我正在尝试在Excel VBA中编写一个macros,添加一个图表,然后要重新命名并编辑列的颜色,但不知怎的,它会引发一个debugging错误。

这是我的代码。 有人可以帮帮我吗:

Sub Charts() ActiveSheet.Shapes.AddCha rt.Select ActiveChart.ChartType = xlColumnStacked100 ActiveChart.SetSourceData Source:=Sheets("Calculations").Range("A1:D11") ActiveChart.Name = "MyChart" ActiveChart.SeriesCollection(1).XValues = "=Data!$N$5:$N$14" ActiveChart.SeriesCollection(3).Select ActiveChart.Legend.Select ActiveChart.Legend.LegendEntries(1).Select With Selection.Format.Fill .Visible = msoTrue .ForeColor.RGB = RGB(255, 0, 0) .Transparency = 0 .Solid End With With Selection.Format.Line .Visible = msoTrue .ForeColor.RGB = RGB(0, 0, 0) .Transparency = 0 End With ActiveChart.Legend.LegendEntries(2).Select With Selection.Format.Fill .Visible = msoTrue .ForeColor.RGB = RGB(255, 192, 0) .Transparency = 0 .Solid End With With Selection.Format.Line .Visible = msoTrue .ForeColor.RGB = RGB(0, 0, 0) .Transparency = 0 End With ActiveChart.Legend.LegendEntries(3).Select With Selection.Format.Fill .Visible = msoTrue .ForeColor.RGB = RGB(0, 176, 80) .Transparency = 0 .Solid End With With Selection.Format.Line .Visible = msoTrue .ForeColor.ObjectThemeColor = msoThemeColorText1 .ForeColor.TintAndShade = 0 .ForeColor.Brightness = 0 .Transparency = 0 End With ActiveChart.SeriesCollection(3).Select ActiveChart.Axes(xlValue).MajorGridlines.Select Selection.Delete End Sub 

谢谢

所以.Name属性只能被设置为Chart Sheets。 对于embedded式图表(图表对象),它是只读的,所以不能为其分配值。 您可以为其容器的名称指定一个值:

 ActiveChart.Parent.Name = "MyChart" 

而不是试图格式化图例条目,自己格式化系列。 我也重写了.with语句,在格式化之前不需要select每个项目:

 Sub ChartThingy() ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlColumnStacked100 ActiveChart.SetSourceData Source:=Sheets("Calculations").Range("A1:D11") ActiveChart.Parent.Name = "MyChart" ActiveChart.SeriesCollection(1).XValues = "=Data!$N$5:$N$14" With ActiveChart.SeriesCollection(3).Format With .Fill .Visible = msoTrue .ForeColor.RGB = RGB(255, 0, 0) .Transparency = 0 .Solid End With With .Line .Visible = msoTrue .ForeColor.RGB = RGB(0, 0, 0) .Transparency = 0 End With End With With ActiveChart.SeriesCollection(2).Format With .Fill .Visible = msoTrue .ForeColor.RGB = RGB(255, 192, 0) .Transparency = 0 .Solid End With With .Line .Visible = msoTrue .ForeColor.RGB = RGB(0, 0, 0) .Transparency = 0 End With End With With ActiveChart.SeriesCollection(1).Format With .Fill .Visible = msoTrue .ForeColor.RGB = RGB(0, 176, 80) .Transparency = 0 .Solid End With With .Line .Visible = msoTrue .ForeColor.ObjectThemeColor = msoThemeColorText1 .ForeColor.TintAndShade = 0 .ForeColor.Brightness = 0 .Transparency = 0 End With End With ActiveChart.Axes(xlValue).MajorGridlines.Select Selection.Delete End Sub