我有以下Sub来创建一个饼图:
Sub CreatePieChart(dataSource As String, chartTitle As String, positionX As Double, positionY As Double)
Dim newChart As Shape
Range(dataSource).Select
Set newChart = ActiveSheet.Shapes.AddChart
With newChart
.Select
.Chart.ChartType = xlPie
.Chart.SetSourceData Source:=Range(dataSource)
.Chart.chartTitle.Select
.Chart.chartTitle.Text = chartTitle
.Chart.SeriesCollection(1).Select
.Chart.SeriesCollection(1).ApplyDataLabels
.Top = positionY
.Left = positionX
End With
End Sub
我第一次调用它时效果很好,但是当我想创建第二个图表时,我收到以下错误:
运行时错误'1004':应用程序定义的错误或对象定义的错误
此行发生错误:
设置newChart = ActiveSheet.Shapes.AddChart
我希望你们能帮助我。 提前致谢
编辑:
第一次打电话:
CreatePieChart“A1:B6”,“first”,10,200
第二次电话:
CreatePieChart“A1:A6,D1:D6”,“second”,10,400
答案 0 :(得分:0)
我找到了一个有效的解决方案,我不知道为什么。我改变的只是我遗漏了所有的选择。新代码:
Sub CreatePieChart(dataSource As String, chartTitle As String, positionX As Double, positionY As Double)
Dim newChart As Shape
Set newChart = ActiveSheet.Shapes.AddChart
With newChart
.Chart.ChartType = xlPie
.Chart.SetSourceData Source:=Range(dataSource)
.Chart.chartTitle.Text = chartTitle
.Chart.SeriesCollection(1).ApplyDataLabels
.Top = positionY
.Left = positionX
End With
End Sub
这真的很奇怪,但至少它现在正在工作。谢谢你的努力。
答案 1 :(得分:0)
在尝试了各种各样的事情之后,我想出了这个解决方案,它与我选择的数据集一起工作(所以我希望它也适合你):
<强>解决方案:强>
Private Sub call_test() ' No interest but to call CreatePieChart
CreatePieChart "A1:B6", "first", 10, 200
CreatePieChart "A1:A6,D1:D6", "second", 10, 400
End Sub
Sub CreatePieChart(dataSource As String, chartTitle As String, positionX As Double, positionY As Double)
Dim newChart As Shape
Set newChart = ActiveSheet.Shapes.AddChart
With newChart
.Chart.ChartType = xlPie
.Chart.SetSourceData Source:=Range(dataSource)
.Chart.chartTitle.Text = chartTitle
.Chart.SeriesCollection(1).ApplyDataLabels
.Top = positionY
.Left = positionX
End With
End Sub
我的数据集:
void void void
1 4 7
2 7 4
3 8 2
4 4 1
5 2 2
6 9 2
导致错误的原因是滥用.Select
:您无法在分离的范围内使用Select
,这就是为什么我没有与之合作"A1:A6,D1:D6"
。我不得不做一些其他修改,但它对我有用。
注意:要选择不连续的范围,请使用Union
:cf Ranges on MSDN