Create In-Cell Chart in Excel using VBA

Vishesh's picture

Paste the following code in a general module and pass the required parameters to create an chart in a cell. This code however works with Excel 2007 onwards.

In-Cell Chart

Sub TestExecute()
    Sheet1.ChartObjects.Delete
    Call CreateInCellChart(Sheet1.Range("A1").CurrentRegion, Selection, xlColumnClustered, xlRows)
End Sub
 
 
Sub CreateInCellChart(rngChtSrc As Range, rngChtTgtCell As Range, lngChartType As Long, bytRowOrColumn As Byte)
    Dim objChart As ChartObject
    If rngChtTgtCell Is Nothing Then Exit Sub
    If rngChtSrc Is Nothing Then Exit Sub
    With rngChtTgtCell.Parent
        Set objChart = .ChartObjects(.Shapes.AddChart.Name)
    End With
    With objChart.Chart
        .ChartType = lngChartType
        .SetSourceData rngChtSrc, bytRowOrColumn
        On Error Resume Next
        .HasTitle = False
        .SetElement (msoElementChartTitleNone)
        .SetElement (msoElementPrimaryValueGridLinesNone)
        .SetElement (msoElementLegendNone)
        .SetElement (msoElementPrimaryCategoryAxisNone)
        .SetElement (msoElementPrimaryValueAxisNone)
        On Error GoTo 0
        .PlotArea.Left = 0
        .PlotArea.Top = 0
        .PlotArea.Height = objChart.Height
        .PlotArea.Width = objChart.Width
    End With
    With objChart
        .ShapeRange.AlternativeText = rngChtTgtCell.Address
        .Left = rngChtTgtCell.Left
        .Top = rngChtTgtCell.Top
        .Height = rngChtTgtCell.Height
        .Width = rngChtTgtCell.Width
    End With
    Set objChart = Nothing
End Sub

AttachmentSize
InCellChart.xlsm18.51 KB