我正在尝试在Excel VBA中编写一个添加图表的宏,然后想要重命名它并编辑列的颜色,但不知何故它会抛出调试错误。
这是我的代码。有人可以帮助我:
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
由于
答案 0 :(得分:1)
因此,只能为图表表设置.Name属性。对于嵌入式图表(图表对象),它是只读的,因此您无法为其分配值。您可以为其分配一个值的容器名称:
ActiveChart.Parent.Name = "MyChart"
不要尝试格式化图例条目,而是自己格式化系列。我还重写了.with语句,在格式化之前无需选择每个项目:
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