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
- 8075 reads
Recent comments
6 years 3 weeks ago
6 years 41 weeks ago
7 years 1 week ago
7 years 4 weeks ago
7 years 5 weeks ago
7 years 10 weeks ago
7 years 18 weeks ago
7 years 19 weeks ago
7 years 19 weeks ago
7 years 19 weeks ago