Create In-Cell Chart in Excel using VBA

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.

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
| Attachment | Size |
|---|---|
| InCellChart.xlsm | 18.51 KB |
»
- Vishesh's blog
- Add new comment
- 1474 reads

Recent comments
2 hours 12 min ago
13 hours 34 min ago
1 day 3 hours ago
1 day 2 hours ago
1 day 5 hours ago
1 day 16 hours ago
1 day 19 hours ago
1 day 19 hours ago
2 days 1 hour ago
2 days 2 hours ago