1
votes

I have two worksheets: PivotTables and Charts. I created,formatted and moved a chart from the PivotTables sheet to the Charts sheet. Now I just want to move it from the default cell to the cells I want but I keep failing in doing so.

When I run the code below I get a run-time error: "Method 'Left' of object 'ChartObject' failed". What am I doing wrong?

Sub CreateChart()

    Sheets("PivotTables").Activate

    Dim myChart2 As chart
    Set myChart2 = Sheets("PivotTables").Shapes.AddChart.chart

    With myChart2
        .SetSourceData Source:=Range("D1").CurrentRegion
        .ChartType = xlColumnClustered
        .HasTitle = True
        .ChartTitle.Text = "Sum of Impressions by Product"
        .SeriesCollection(1).Format.Fill.ForeColor.RGB = rgbBlue
        .ShowAllFieldButtons = False
        .Location xlLocationAsObject, "Charts"
    End With

    Sheets("Charts").Activate

    With myChart2.Parent
        .Left = Sheets("Charts").Range("F1").Left
        .Top = Sheets("Charts").Range("F1").Top
        .Width = Sheets("Charts").Range("F1:J1").Width
        .Height = Sheets("Charts").Range("F1:F10").Height
    End With

End Sub
2

2 Answers

1
votes

Your code performs somethings different from your text description.

  1. You create a chart "Chart2" on the worksheet "Pivottables"
  2. you should copy or cut the chart from this worksheet
  3. Then you can use "paste" or "pastespecial" to insert the chart in worksheet "charts"
  4. Now you can format and/or shift position on this worksheet

When you change left, top etc. it doesn't move the chart from sheet to sheet

1
votes

I can't quite answer the why, but there seemed to be a conflict in the ordering between .Location xlLocationAsObject, "Charts" and the position setting with .left/etc

Moving the chart on the sheet prior to moving it between sheets with .location seemed to fix your problem.

Sub CreateChart()

    Sheets("PivotTables").Activate

    Dim myChart2 As chart
    Set myChart2 = Sheets("PivotTables").Shapes.AddChart.chart

    With myChart2
        .SetSourceData Source:=Range("D1").CurrentRegion
        .ChartType = xlColumnClustered
        .HasTitle = True
        .ChartTitle.Text = "Sum of Impressions by Product"
        .SeriesCollection(1).Format.Fill.ForeColor.RGB = rgbBlue
        .ShowAllFieldButtons = False
        With .Parent
           .Left = Sheets("Charts").Range("F1").Left
           .Top = Sheets("Charts").Range("F1").Top
           .Width = Sheets("Charts").Range("F1:J1").Width
           .Height = Sheets("Charts").Range("F1:F10").Height
        End With
        .Location xlLocationAsObject, "Charts"
    End With

    Sheets("Charts").Activate



End Sub