【问题标题】:Sub for Creating a Pie Chart用于创建饼图的子
【发布时间】:2014-08-19 16:06:52
【问题描述】:

我有以下子来创建饼图:

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

【问题讨论】:

  • 你能把不同的调用添加到CreatePieChart,看看每次都传递了哪些参数吗?
  • 你的代码对我来说很好。

标签: vba excel


【解决方案1】:

在尝试了各种方法后,我想出了这个解决方案,它适用于我选择的数据集(所以我希望它也适用于你):

解决方案:

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

【讨论】:

  • 谢谢!刚刚发现 Select 的东西导致了错误,但不知道为什么;)
  • @oHoodie 很高兴您自己找到了解决方案。我的建议是尽量避免使用Select,它的效率并不高,并且可能导致难以跟踪错误
【解决方案2】:

嗯,我找到了一个有效的解决方案,我只是不知道为什么。我唯一改变的是我忽略了所有的选择。新代码:

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

这真的很奇怪,但至少它现在可以工作了。感谢您的努力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2021-07-17
    相关资源
    最近更新 更多