VBA course · Lesson 25 of 33

Create and format charts with VBA

Create charts with AddChart2 and ChartObjects, set data and chart type, format titles, axes and series, export to PNG and make one chart per region.

Advanced 20 min read

Making one chart by hand takes a minute. Making the same chart for twelve regions every month, with the same colours, titles and size, and then pasting them into a report, takes an afternoon, and no two end up quite alike. That is a perfect job for VBA. A macro can build charts from scratch, point them at the right data, format every detail and save them as image files ready for an email or a slide.

In this lesson you will learn how charts are organised in the object model, create a chart in two ways, choose the chart type, format titles, axes and series, add series one at a time, export charts as PNG files, generate one chart per region in a loop and clean up old charts. You should be comfortable with ranges and loops (Range and Cells: working with cells in VBA, For loops: For...Next and For Each) and with finding the end of your data (Find the last row and build dynamic ranges in VBA).

We use this monthly sales summary on a sheet named Summary:

ABCDE
1MonthNorthSouthEastWest
2Jul42352831
3Aug45333029
4Sep48373234
5Oct51363533
6Nov55403736

Summary sheet: monthly sales per region (thousands)

How charts are organised

A chart that sits on a worksheet lives inside a container called a ChartObject. The ChartObject is the box: its position, size and name. Inside it is the Chart, which holds everything you see: the chart type, the series, the axes, the title and the legend. The worksheet also lists the same box in its Shapes collection, because every chart is a kind of shape.

ObjectWhat it isExample
ws.ChartObjectsAll embedded charts on a sheetws.ChartObjects.Count
ChartObjectThe box: Left, Top, Width, Height, Nameco.Width = 480
ChartThe chart inside the boxco.Chart.ChartType
SeriesCollectionAll data series of a chartcht.SeriesCollection(1)
Axes(xlValue)The value axis (usually vertical).MaximumScale = 60
Axes(xlCategory)The category axis (usually horizontal).TickLabels.Font.Size

There is also a separate kind of chart that fills its own chart sheet (Charts.Add), but embedded charts on a worksheet are far more common in reports, so this lesson focuses on those.

Creating a chart: Shapes.AddChart2

Shapes.AddChart2 (Excel 2013 and later) creates a chart with the modern default look. It takes a style number (-1 for the default), the chart type, and the position and size in points (1 point is 1/72 inch, roughly 1.33 pixels on a normal screen).

VBA
Option Explicit

Sub CreateSalesChart()
    Dim ws As Worksheet
    Dim shp As Shape
    Dim cht As Chart

    Set ws = ThisWorkbook.Worksheets("Summary")

    Set shp = ws.Shapes.AddChart2(Style:=-1, XlChartType:=xlColumnClustered, _
        Left:=ws.Range("G2").Left, Top:=ws.Range("G2").Top, _
        Width:=480, Height:=280)

    Set cht = shp.Chart
    cht.SetSourceData Source:=ws.Range("A1").CurrentRegion, PlotBy:=xlColumns

    cht.HasTitle = True
    cht.ChartTitle.Text = "Sales by region, Jul to Nov 2026 (thousands)"
    shp.Name = "chtSalesByRegion"
End Sub
A clustered column chart of all regions, placed to the right of the data

Using ws.Range("G2").Left and .Top places the chart exactly over cell G2, which is far more reliable than guessing pixel numbers: if someone widens column A, the chart still lands in G2. SetSourceData tells the chart where its data is. PlotBy:=xlColumns makes each column (North, South, East, West) a series and each row a category on the horizontal axis. With xlRows you would get one series per month instead.

Giving the shape a name (chtSalesByRegion) lets later code find it with ws.ChartObjects("chtSalesByRegion") instead of relying on a number like ChartObjects(1), which changes when charts are added or deleted.

Creating a chart: ChartObjects.Add

The older method, ChartObjects.Add, works in every version back to Excel 2007 and is still widely used. It creates an empty box; you set the type and data afterwards.

VBA
Sub CreateNorthLineChart()
    Dim ws As Worksheet
    Dim co As ChartObject

    Set ws = ThisWorkbook.Worksheets("Summary")
    Set co = ws.ChartObjects.Add(Left:=ws.Range("G22").Left, _
        Top:=ws.Range("G22").Top, Width:=420, Height:=240)
    co.Name = "chtNorthTrend"

    With co.Chart
        .ChartType = xlLineMarkers
        .SetSourceData Source:=ws.Range("A1:B6")
        .HasTitle = True
        .ChartTitle.Text = "North: monthly sales"
        .HasLegend = False
    End With
End Sub
A line chart for North only, using ChartObjects.Add

The range A1:B6 has the month names in column A and North in column B. Excel uses the first column as categories and the header North as the series name. One series needs no legend, so HasLegend = False gives the plot more space.

Chart type constants you will use

ConstantChart
xlColumnClusteredVertical bars side by side
xlColumnStackedVertical bars stacked on top of each other
xlBarClusteredHorizontal bars
xlLine / xlLineMarkersLine, without or with markers
xlPie / xlDoughnutPie and doughnut (one series)
xlXYScatterScatter (x and y are both numbers)
xlAreaArea

You can change the type of an existing chart at any time with cht.ChartType = xlBarClustered. For a combination chart, change the type of a single series: cht.SeriesCollection("North").ChartType = xlLine.

Formatting titles, axes and series

A default chart is rarely report-ready. The following macro takes the chart made earlier and gives it a consistent house style.

VBA
Sub FormatSalesChart()
    Dim cht As Chart
    Dim i As Long
    Dim colours As Variant

    Set cht = ThisWorkbook.Worksheets("Summary").ChartObjects("chtSalesByRegion").Chart
    colours = Array(RGB(31, 78, 121), RGB(46, 134, 171), RGB(242, 169, 0), RGB(122, 122, 122))

    With cht.ChartTitle
        .Text = "Sales by region (thousands)"
        .Format.TextFrame2.TextRange.Font.Size = 14
        .Format.TextFrame2.TextRange.Font.Bold = msoTrue
    End With

    With cht.Axes(xlValue)
        .MinimumScale = 0
        .MaximumScale = 60
        .MajorUnit = 10
        .HasTitle = True
        .AxisTitle.Text = "Sales (thousands)"
        .TickLabels.NumberFormat = "#,##0"
        .MajorGridlines.Format.Line.ForeColor.RGB = RGB(217, 217, 217)
    End With

    cht.Axes(xlCategory).TickLabels.Font.Size = 10
    cht.Legend.Position = xlLegendPositionBottom

    For i = 1 To cht.SeriesCollection.Count
        cht.SeriesCollection(i).Format.Fill.ForeColor.RGB = colours(i - 1)
    Next i
End Sub
Format an existing chart: title, axes, gridlines, legend and colours

A few points worth noticing:

  • MinimumScale = 0 stops Excel from starting the axis at, say, 25, which exaggerates small differences.
  • Fixing MaximumScale makes several charts comparable, because they share the same scale. Leave it automatic if the numbers vary a lot.
  • Format.Fill.ForeColor.RGB colours bars and areas. For a line series use .Format.Line.ForeColor.RGB instead.
  • The colours array is zero-based while SeriesCollection starts at 1, hence colours(i - 1).

Data labels

VBA
Sub LabelNovember()
    Dim cht As Chart
    Dim i As Long

    Set cht = ThisWorkbook.Worksheets("Summary").ChartObjects("chtSalesByRegion").Chart
    For i = 1 To cht.SeriesCollection.Count
        With cht.SeriesCollection(i).Points(5)    ' the fifth category is Nov
            .HasDataLabel = True
            .DataLabel.Font.Size = 9
        End With
    Next i
End Sub
Show values on top of the November bars only

Points(5) is the fifth data point of each series. To label every point, set cht.SeriesCollection(i).HasDataLabels = True instead.

Adding series one at a time

SetSourceData is easiest for a neat block. When the data is scattered, or you want to choose exactly which columns appear, add each series yourself with SeriesCollection.NewSeries.

VBA
Sub NorthVersusWest()
    Dim ws As Worksheet
    Dim co As ChartObject
    Dim s As Series

    Set ws = ThisWorkbook.Worksheets("Summary")
    Set co = ws.ChartObjects.Add(Left:=ws.Range("G40").Left, _
        Top:=ws.Range("G40").Top, Width:=420, Height:=240)

    With co.Chart
        .ChartType = xlLine
        ' Remove any series Excel guessed from the current selection
        Do While .SeriesCollection.Count > 0
            .SeriesCollection(1).Delete
        Loop

        Set s = .SeriesCollection.NewSeries
        s.Name = "=Summary!$B$1"
        s.Values = ws.Range("B2:B6")
        s.XValues = ws.Range("A2:A6")

        Set s = .SeriesCollection.NewSeries
        s.Name = "=Summary!$E$1"
        s.Values = ws.Range("E2:E6")
        s.XValues = ws.Range("A2:A6")
    End With
End Sub
Build a chart of North and West only, series by series

Values are the numbers, XValues the category labels and Name the series name. Writing the name as a formula (=Summary!$B$1) links it to the header cell, so renaming the region in the sheet renames the series. The Do While loop at the top matters: if the user had a data range selected when the macro ran, Excel may already have added series of its own to the new chart.

Exporting a chart as an image

Chart.Export saves the chart as a picture file, ready to attach to an email (Control Outlook, Word and PowerPoint from Excel VBA) or insert into a slide.

VBA
Sub ExportSalesChart()
    Dim cht As Chart
    Dim filePath As String

    Set cht = ThisWorkbook.Worksheets("Summary").ChartObjects("chtSalesByRegion").Chart
    filePath = ThisWorkbook.Path & Application.PathSeparator & _
        "Sales_by_region_" & Format(Date, "yyyy-mm") & ".png"

    cht.Export Filename:=filePath, FilterName:="PNG"
    MsgBox "Saved " & filePath
End Sub
Save the chart as a PNG next to the workbook

ThisWorkbook.Path is empty for a workbook that has never been saved, so save the workbook first. Application.PathSeparator returns \ on Windows and / on a Mac, which keeps the code portable. The image has the same size as the chart on screen; make the ChartObject larger before exporting if you need a sharper picture.

Note. On a Mac, sandboxing means Excel may only write to certain folders without asking. Exporting next to a workbook in your Documents folder normally works; other folders may show a permission prompt the first time. See Files and folders: open, save, loop through files and write text files.

One chart per region in a loop

Here everything comes together: one small line chart for each region column, laid out in a grid, each named after its region.

VBA
Sub ChartPerRegion()
    Dim ws As Worksheet
    Dim co As ChartObject
    Dim lastRow As Long
    Dim lastCol As Long
    Dim col As Long
    Dim n As Long
    Const CHART_W As Double = 260
    Const CHART_H As Double = 170
    Const GAP As Double = 12

    Set ws = ThisWorkbook.Worksheets("Summary")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column

    For col = 2 To lastCol
        Set co = ws.ChartObjects.Add( _
            Left:=ws.Range("G2").Left + (n Mod 3) * (CHART_W + GAP), _
            Top:=ws.Range("G2").Top + (n \ 3) * (CHART_H + GAP), _
            Width:=CHART_W, Height:=CHART_H)
        co.Name = "chtRegion_" & ws.Cells(1, col).Value

        With co.Chart
            .ChartType = xlLineMarkers
            .SetSourceData Source:=Union(ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, 1)), _
                ws.Range(ws.Cells(1, col), ws.Cells(lastRow, col)))
            .HasTitle = True
            .ChartTitle.Text = ws.Cells(1, col).Value
            .HasLegend = False
            .Axes(xlValue).MinimumScale = 0
        End With
        n = n + 1
    Next col
End Sub
Create a small chart for every region column, three per row

n Mod 3 gives 0, 1, 2, 0, 1, ... so charts move right three times and then wrap. n \ 3 (integer division) gives 0, 0, 0, 1, 1, ... so every three charts the row moves down. Union joins the month column and the region column into one source range even though they are not next to each other. With the four regions here you get three charts in the first row and one in the second; with twelve regions the same code makes four rows.

Deleting charts

Before you rebuild charts, delete the old ones, otherwise every run piles new charts on top of the last.

VBA
Sub DeleteRegionCharts()
    Dim ws As Worksheet
    Dim i As Long

    Set ws = ThisWorkbook.Worksheets("Summary")

    ' Loop backwards: deleting changes the numbering of the remaining charts
    For i = ws.ChartObjects.Count To 1 Step -1
        If ws.ChartObjects(i).Name Like "chtRegion_*" Then
            ws.ChartObjects(i).Delete
        End If
    Next i

    ' To delete every chart on the sheet in one go:
    ' ws.ChartObjects.Delete
End Sub
Delete all charts on a sheet, or only those whose name starts with chtRegion_

Looping backwards is the safe pattern whenever you delete items from a collection while walking through it (For loops: For...Next and For Each). Like with * matches any name that starts with chtRegion_.

Common mistakes

  • Referring to charts by number (ChartObjects(1)) in code that other macros also touch. Name your charts.
  • Forgetting that a new chart may already contain series from the current selection.
  • Setting .Format.Fill on a line series, which has no visible fill. Use .Format.Line.
  • Placing charts with fixed points instead of cell positions, so they drift when columns are resized.
  • Exporting from an unsaved workbook, where ThisWorkbook.Path is an empty string.
  • Using the macro recorder's ActiveChart and Select lines unchanged. They break as soon as a different chart is active; keep the chart in a variable instead (The macro recorder: record, read and clean up code).
Tip. If your data is an Excel table, point the chart at the table (SetSourceData lo.Range). The chart then grows with the table, and you may not need to rebuild it at all.

Check yourself

1. What is the difference between a ChartObject and a Chart?

2. What does PlotBy:=xlColumns do in SetSourceData?

3. Why do you loop backwards when deleting charts by index?

4. Which statement saves a chart as a PNG file?

5. To colour a line series red, which property do you set?