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
- Login or register to post comments
- 8049 reads
Recent comments
5 years 51 weeks ago
6 years 37 weeks ago
6 years 49 weeks ago
6 years 51 weeks ago
7 years 5 days ago
7 years 6 weeks ago
7 years 14 weeks ago
7 years 14 weeks ago
7 years 15 weeks ago
7 years 15 weeks ago