VBA创建图表错误

时间:2018-08-10 10:37:42

标签: excel vba excel-vba excel-charts

我正在尝试从数据透视表创建图表,但出现错误。我的代码如下:

Sub Chart()
'
' chart Macro
  Dim shp As Chart

'
    Set shp = Charts.Add
    Worksheets("pivot").Select
    Range("B5:E5").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlColumnClustered
    ActiveChart.SetSourceData Source:=Range("Pivot!$A$3:$E$5")
    ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Tools Sold"
    With ActiveChart
    .HasTitle = True
    .ChartTitle.Characters.Text = "Consolidated"

    ActiveSheet.Shapes("charts").LockAspectRatio = msoTrue
    ActiveChart.ShowValueFieldButtons = False
    ActiveSheet.ChartObjects("charts").Activate
    ActiveChart.SeriesCollection(1).Select
    ActiveChart.SeriesCollection(1).ApplyDataLabels
    ActiveChart.SeriesCollection(2).Select
    ActiveChart.SeriesCollection(2).ApplyDataLabels
    ActiveChart.SeriesCollection(3).Select
    ActiveChart.SeriesCollection(3).ApplyDataLabels

    End With
End Sub

调试线路时出现运行时错误

ActiveSheet.Shapes("charts").LockAspectRatio = msoTrue

我是初学者。因此无法解决此问题。我还附有错误屏幕截图和该行。 如何解决这个问题? enter image description here

3 个答案:

答案 0 :(得分:2)

在错误消息之前添加这些行,并使用cht.Name给出的名称引用您的图表

cache-control

答案 1 :(得分:1)

我建议您在尝试自动执行Excel的任何内置任务时,不要尝试自己找出确切的VBA,而应使用 Macro Recorder 将操作记录为您可以手动执行步骤 (在这种情况下,请使用数据透视表创建图表),然后根据需要查看和编辑生成的代码。


编辑:

如果不确定图表的名称,一种查找方法是运行以下命令:

Sub ListCharts()
    Dim x
    For Each x In ActiveSheet.ChartObjects
      Debug.Print x.Name
    Next x
End Sub

使用 Ctrl + G 打开立即窗口以查看结果(如果尚未打开)。


更多信息:

答案 2 :(得分:0)

您不需要任何形状对象,也不需要所有激活/选择

With Worksheets("pivot").Shapes.AddChart.Chart
    .ChartType = xlColumnClustered
    .SetSourceData Source:=Range("Pivot!$A$3:$E$5")
    .HasTitle = True
    .ChartTitle.Characters.Text = "Consolidated"
    .SeriesCollection(1).ApplyDataLabels
    .SeriesCollection(2).ApplyDataLabels
    .SeriesCollection(3).ApplyDataLabels
    .Location Where:=xlLocationAsNewSheet, Name:="Tools Sold"
End With