Preston
Preston

Reputation: 8187

Refer to a programatically added chart

I use the below code to insert a chart. How do I now refer to said chart? I understand that I should use the ChartObject, but how do I set this?

To be more specific, I'd like to assign the chart to a variable, but I'm unsure how to do this. I have tried:

set myChart = ActiveSheet.Shapes.AddChart(xlLine, 500, 420, , 175)

but to no avail.

Sub InsertInfection(rngToPrint As Range, lngTopLeft As String, BottomLeft As String)
    Dim strRange As String
    Dim rngChart As Range
    Dim myChart As ChartObject

    lngStartRow = Sheets(rngToPrint.Worksheet.Name).Range(lngTopLeft).Row
    lngEndRow = Sheets(rngToPrint.Worksheet.Name).Range(BottomLeft).Row

    Sheets(rngToPrint.Worksheet.Name).Activate
    Sheets(rngToPrint.Worksheet.Name).Range("$A$" & CStr(lngStartRow) & ":$D$" & CStr(lngEndRow)).Select

    ActiveSheet.Shapes.AddChart(xlLine, 500, 420, , 175).Select

End Sub

Upvotes: 0

Views: 32

Answers (1)

Rory
Rory

Reputation: 34045

Like this

Dim myChart as Chart
set myChart = ActiveSheet.Shapes.AddChart(xlLine, 500, 420, , 175).Chart

If you need a reference to the ChartObject, use myChart.Parent

Upvotes: 2

Related Questions