Tabellab

ChartObjects and the Chart Inside Them

Lesson 1 of 7Reading

A chart on a sheet is two objects

This catches everyone once. The box floating on your worksheet is a ChartObject — a container, like a picture frame, with a position, a size, a name and a border. The picture inside the frame is the Chart, and that is what owns the series, the axes, the title and the type.

  • ChartObject — .Left, .Top, .Width, .Height, .Name, .Delete.
  • Chart — .ChartType, .SetSourceData, .SeriesCollection, .Axes, .ChartTitle, .Export.
  • The bridge — co.Chart gets from the frame to the picture, ch.Parent back again.
  • The rule — where the chart sits is the ChartObject, what the chart shows is the Chart. co.ChartType fails and so does ch.Left.

First, something to look at

Run this once to get a sheet with data and two badly placed charts on it. Lessons 2 and 3 explain these four chart lines properly; here they are only there to give the next macro some work.

Option Explicit

Sub MakeChartDemo()
    Dim ws As Worksheet
    Dim co As ChartObject
    Dim r As Long

    Set ws = ThisWorkbook.Worksheets.Add( _
        After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
    ws.Name = "Chart Demo " & Format(Now, "hhmmss")

    ws.Range("A1:B1").Value = Array("Month", "Revenue")
    For r = 2 To 13
        ws.Cells(r, 1).Value = Format(DateSerial(2026, r - 1, 1), "mmm")
        ws.Cells(r, 2).Value = 1000 + r * 137
    Next r

    Set co = ws.ChartObjects.Add(Left:=200, Top:=20, Width:=300, Height:=180)
    co.Chart.SetSourceData Source:=ws.Range("A1:B13")
    co.Chart.ChartType = xlColumnClustered

    Set co = ws.ChartObjects.Add(Left:=260, Top:=90, Width:=250, Height:=150)
    co.Chart.SetSourceData Source:=ws.Range("A1:B13")
    co.Chart.ChartType = xlLine
End Sub

The macro: line up every chart in the workbook

Dragging charts until they are the same size is a job nobody should do twice. This walks every worksheet, gives each chart a predictable name, snaps it to the same width, height and left edge, stacks the charts down the sheet and prints an inventory.

Sub TidyAllCharts()
    Dim ws As Worksheet
    Dim co As ChartObject
    Dim ch As Chart
    Dim anchor As Range
    Dim n As Long
    Dim total As Long

    For Each ws In ThisWorkbook.Worksheets
        Set anchor = ws.Range("H2")
        n = 0

        For Each co In ws.ChartObjects
            n = n + 1
            total = total + 1
            Set ch = co.Chart

            co.Name = "cht" & Format(ws.Index, "00") & "_" & Format(n, "00")
            co.Left = anchor.Left
            co.Top = anchor.Top + (n - 1) * 280
            co.Width = 440
            co.Height = 260

            Debug.Print ws.Name & " | " & co.Name & _
                        " | type " & ch.ChartType & _
                        " | series " & ch.SeriesCollection.Count & _
                        " | has title " & ch.HasTitle
        Next co
    Next ws

    MsgBox total & " chart(s) aligned. Details are in the Immediate window, " & _
           "which you open with Ctrl+G in the VBA editor.", vbInformation
End Sub

Line by line

  • For Each co In ws.ChartObjects — ChartObjects is a worksheet collection. Charts on their own full-page tab are not in it: those sit in ThisWorkbook.Charts, and this macro leaves them alone.
  • Set ch = co.Chart is the single line that crosses from the frame to the picture. Everything above it is geometry, everything below it is content.
  • co.Name = "cht" & ... gives every frame a predictable name, so later code can say ws.ChartObjects("cht01_01") instead of trusting an index that shifts as soon as somebody deletes a chart. If code in your workbook already refers to charts by name, comment this line out first.
  • co.Left = anchor.Left and co.Top = anchor.Top position the frame against cell H2 rather than at a guessed number. Reading geometry off a cell is the trick worth stealing here.
  • + (n - 1) * 280 stacks the charts downwards, leaving 20 points of air between two charts 260 points high.
  • co.Width and co.Height are in points, not pixels — 72 to the inch, identical on every screen. Sizing in code is the only way to make a report look the same on two machines.
  • ch.ChartType, ch.SeriesCollection.Count and ch.HasTitle are all read from the Chart. Ask co for any of them and you get error 438.
  • Debug.Print writes to the Immediate window; the MsgBox reports only the count, because a message box holding forty charts helps nobody.

The trap: ActiveChart is usually Nothing

Start the macro recorder, click a chart, change its title, and the recording hands you ActiveChart.ChartTitle.Text = "Revenue". It works while the chart is selected. Assign the very same macro to a button and it stops at run-time error 91, "Object variable or With block variable not set" — clicking the button deselected the chart, so ActiveChart is Nothing. Same code, same workbook, and nothing on screen explains the difference.

' Recorded: depends on whatever happens to be selected
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "Revenue"

' Written: depends on nothing at all
Dim ch As Chart

Set ch = ThisWorkbook.Worksheets(1).ChartObjects(1).Chart
ch.HasTitle = True
ch.ChartTitle.Text = "Revenue"

Select and Activate are the recorder's way of pointing at things, because pointing is all it can see you do. A variable is better in every way: set the object once, use it as often as you like, and the macro stops caring what the user clicked last — and runs faster, because Excel is not redrawing a selection each time.

The bridge works both ways: ch.Parent is the ChartObject, so a routine that was handed a Chart can still resize its frame with ch.Parent.Width = 440.

How this course goes on

This lesson takes stock of charts that already exist; lesson 2 creates them from nothing, comparing the old ChartObjects.Add with the newer Shapes.AddChart2. Lesson 3 feeds a chart with SetSourceData, including the PlotBy setting that decides whether twelve months become twelve series or one — the difference between a readable chart and an absurd one. After that come chart types, titles, axes and the legend, formatting individual series, and exporting a finished chart as an image file.

Who this lesson is for, and the problem with hand-made charts

Every month the same report, every month the same charts, and every month they look a little different. One is a few pixels wider, one has lost its title, one sits on top of the table it is meant to illustrate. Someone spends half an hour dragging frames and clicking through format dialogs, and the next person to open the file changes it all again. If you build recurring reports in Excel and have written or recorded a simple macro, this course is for you. It shows how to create, size, format and export charts from VBA, so that every report looks identical every time.

This free first lesson starts with the part almost everyone gets wrong: what a chart on a sheet actually is in VBA. Once you know that it is two objects, not one, the error messages make sense, the code from the macro recorder makes sense, and you can write a macro that lines up every chart in a workbook in a fraction of a second. That macro is the lab above, and this article walks through it with real numbers.

The core idea: a frame and a picture

The box floating on your worksheet is a ChartObject. Think of it as a picture frame. It has a position, a size, a name and a border, and it belongs to the worksheet's ChartObjects collection. Inside the frame is the Chart, the picture itself. The Chart owns everything you see inside: the chart type, the series, the axes, the title and the legend.

The rule that follows is short and saves hours: where a chart sits is the ChartObject, what it shows is the Chart. co.Left, co.Width and co.Name work on the frame. ch.ChartType, ch.SetSourceData and ch.ChartTitle work on the picture. Ask the frame for its chart type and VBA stops with run-time error 438, "Object doesn't support this property or method". You cross from one to the other with co.Chart, and back again with ch.Parent.

There is one more kind of chart: a chart sheet, a whole tab that contains nothing but a chart. It has no frame, because the sheet itself plays that role, and you find it in ThisWorkbook.Charts, not in any worksheet's ChartObjects. The lab macro deliberately leaves chart sheets alone.

The worked example: twelve months of revenue

The lab begins with MakeChartDemo. It adds a sheet, writes a Month and a Revenue column, and creates two charts from the same data, on purpose in awkward places. The revenue for each row r is 1000 + r * 137, so the numbers are easy to check. In an English-language Excel the months appear as Jan to Dec, because Format(DateSerial(2026, r - 1, 1), "mmm") returns the short month name in the language of your system.

RowA: MonthB: RevenueFormula behind it
2Jan1,2741000 + 2 * 137
3Feb1,4111000 + 3 * 137
4Mar1,5481000 + 4 * 137
5Apr1,6851000 + 5 * 137
6May1,8221000 + 6 * 137
7Jun1,9591000 + 7 * 137
8Jul2,0961000 + 8 * 137
9Aug2,2331000 + 9 * 137
10Sep2,3701000 + 10 * 137
11Oct2,5071000 + 11 * 137
12Nov2,6441000 + 12 * 137
13Dec2,7811000 + 13 * 137

Revenue climbs by exactly 137 every month, from 1,274 in January to 2,781 in December, 24,330 for the year. You can check the total on the sheet with =SUM(B2:B13) and the average with =AVERAGE(B2:B13), which gives 2,027.5. The first chart the demo creates is a clustered column chart of this range, like the one below. The second is a line chart of the same numbers, placed so that it covers part of the first.

Revenue by month, as MakeChartDemo writes itRevenue (example values)03,0001,274Jan1,411Feb1,548Mar1,685Apr1,822May1,959Jun2,096Jul2,233Aug2,370Sep2,507Oct2,644Nov2,781Dec
The demo data as a clustered column chart: one series called Revenue, twelve categories. The values are example numbers generated by the lab macro.

These are the lines that create the first chart. They already show the two-object rule at work: ChartObjects.Add creates the frame, and everything after co.Chart configures the picture.

Set co = ws.ChartObjects.Add(Left:=200, Top:=20, Width:=300, Height:=180)
co.Chart.SetSourceData Source:=ws.Range("A1:B13")
co.Chart.ChartType = xlColumnClustered

The macro: line up every chart in the workbook

TidyAllCharts walks every worksheet, renames each chart frame in a predictable way, gives all of them the same size and left edge, stacks them down the sheet starting at cell H2, and prints an inventory to the Immediate window. Here is the whole macro from the lab:

Sub TidyAllCharts()
    Dim ws As Worksheet
    Dim co As ChartObject
    Dim ch As Chart
    Dim anchor As Range
    Dim n As Long
    Dim total As Long

    For Each ws In ThisWorkbook.Worksheets
        Set anchor = ws.Range("H2")
        n = 0

        For Each co In ws.ChartObjects
            n = n + 1
            total = total + 1
            Set ch = co.Chart

            co.Name = "cht" & Format(ws.Index, "00") & "_" & Format(n, "00")
            co.Left = anchor.Left
            co.Top = anchor.Top + (n - 1) * 280
            co.Width = 440
            co.Height = 260

            Debug.Print ws.Name & " | " & co.Name & _
                        " | type " & ch.ChartType & _
                        " | series " & ch.SeriesCollection.Count & _
                        " | has title " & ch.HasTitle
        Next co
    Next ws

    MsgBox total & " chart(s) aligned. Details are in the Immediate window, " & _
           "which you open with Ctrl+G in the VBA editor.", vbInformation
End Sub

The table compares the two demo charts before and after the macro. The "after" positions assume default column widths and row heights, where column H starts about 336 points from the left edge of the sheet and row 2 about 15 points from the top. Your numbers will differ if you have widened any columns, which is exactly why the macro reads the position from the cell instead of hard-coding it.

ChartNameLeftTopWidthHeightChartType
1 beforeChart 1 (Excel default)2002030018051 (xlColumnClustered)
2 beforeChart 2 (Excel default)260902501504 (xlLine)
1 aftercht02_01 (for example)≈ 336≈ 1544026051, unchanged
2 aftercht02_02 (for example)≈ 336≈ 2954402604, unchanged

The name depends on the position of the sheet in the workbook. If the demo sheet is the second tab, ws.Index is 2 and the frames become cht02_01 and cht02_02. The chart type column shows that the macro never touched the picture: it moved frames only, and read from the Chart for the printout.

Chart positions before and after TidyAllChartsBefore: placed by handA1:B13After: anchored to H2A1:B131: 300 x 1802: 250 x 150cht02_01440 x 260cht02_02440 x 260
Before the macro the two frames overlap and differ in size. After it, both are 440 by 260 points, share the left edge of H2 and sit 280 points apart, which leaves 20 points of space between them. Drawn to scale, assuming default column widths.

Line by line: what each part does

  • For Each co In ws.ChartObjects loops through the frames on one worksheet. Charts on chart sheets are not in this collection.
  • Set ch = co.Chart is the bridge from frame to picture. Everything that sets position and size uses co, everything that reads content uses ch.
  • co.Name = "cht" & Format(ws.Index, "00") & "_" & Format(n, "00") gives a stable name. Later code can say ws.ChartObjects("cht02_01") instead of relying on an index that shifts when someone deletes a chart. If other code already refers to charts by their old names, comment this line out first.
  • co.Left = anchor.Left borrows the position of cell H2. Every Range has Left, Top, Width and Height in points, so cells make perfect anchors.
  • (n - 1) * 280 places the first chart at H2, the second 280 points lower, and so on. With a height of 260, that leaves a 20-point gap.
  • co.Width = 440 and co.Height = 260 are in points. 72 points make an inch, so a chart 440 points wide is a little over six inches on paper, on every screen.
  • ch.ChartType prints as a number, because chart type constants are numbers: 51 for a clustered column, 4 for a line. ch.SeriesCollection.Count is 1 for both demo charts.
  • Debug.Print writes one line per chart to the Immediate window. The MsgBox only reports the total, because a dialog listing forty charts helps nobody.

Adapting the macro to your own reports

The tidy macro is short on purpose, so it is easy to bend to a real workbook. Three changes cover most needs. To lay charts out in a grid of two columns instead of one long column, replace the two position lines with these, which use Mod for the column and integer division \ for the row:

co.Left = anchor.Left + ((n - 1) Mod 2) * 460
co.Top = anchor.Top + ((n - 1) \ 2) * 280

To leave a sheet untouched, for example a cover page with a hand-placed logo chart, add If ws.Name = "Cover" Then GoTo NextSheet at the top of the outer loop and put the label NextSheet: just before Next ws. And to make the anchor follow your layout instead of a fixed cell, give a cell the defined name ChartAnchor on each sheet and use Set anchor = ws.Range("ChartAnchor"). Insert or delete columns, and the charts move with the named cell next time you run the macro.

Step by step: run it in your own workbook

  1. Open a new workbook and save it as Excel Macro-Enabled Workbook (*.xlsm) with F12.
  2. Press Alt+F11 (Mac: Opt+F11) to open the VBA editor, select your workbook in the Project Explorer and choose Insert → Module.
  3. Paste MakeChartDemo and TidyAllCharts from the lab into the module, with one Option Explicit at the top.
  4. Click inside MakeChartDemo and press F5. A new sheet named Chart Demo plus a time stamp appears, with data in A1:B13 and two overlapping charts.
  5. Back in Excel, click one chart and look at the Name Box left of the formula bar. It shows the default frame name, such as Chart 1. Press Esc to deselect.
  6. Press Alt+F8, choose TidyAllCharts and click Run. The message box reports how many charts were aligned.
  7. Return to the editor and press Ctrl+G. The Immediate window lists each chart with its new name, type and series count.
  8. Click a chart again: the Name Box now shows cht02_01 or similar, and Chart Format → Size on the ribbon shows the new height and width. The ribbon displays them in your unit of measure, such as centimetres or inches, not in points.
To reach the Selection Pane, which lists every chart frame on a sheet by name, use Home → Find & Select → Selection Pane or Alt+F10 on Windows. It is the quickest way to confirm the names your macro gave.

Excel charts with VBA course: charts created, aligned and formatted by a macro
When charts are built by code, every monthly report has the same size, position and style.

The trap: ActiveChart is usually Nothing

Start the macro recorder, click a chart, type a new title and stop recording. The recorder gives you ActiveChart.ChartTitle.Text = "Revenue". It works while the chart is selected. Assign the same macro to a button and it stops with run-time error 91, "Object variable or With block variable not set". Clicking the button deselected the chart, so ActiveChart is Nothing. Same code, same workbook, and nothing on screen explains the difference.

' Recorded: depends on whatever happens to be selected
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = "Revenue"

' Written: depends on nothing at all
Dim ch As Chart

Set ch = ThisWorkbook.Worksheets(1).ChartObjects(1).Chart
ch.HasTitle = True
ch.ChartTitle.Text = "Revenue"

The recorder uses Select and Activate because pointing is all it can see you do. A variable is better in every way: you set the object once, use it as often as you like, and the macro no longer cares what the user clicked last. It also runs faster, because Excel does not redraw a selection for every step. After TidyAllCharts has run, you can even write ws.ChartObjects("cht02_01").Chart and never depend on an index again.

Other common mistakes, and how to spot them

  • Mixing up frame and picture. co.ChartType = xlLine or ch.Left = 100 both raise error 438. If you see 438 on a chart line, check whether the property belongs to the ChartObject or to the Chart.
  • Looking for chart sheets in ChartObjects. A loop over ws.ChartObjects never finds a chart that has its own tab. Symptom: the count in the message box is lower than the number of charts you can see. Loop over ThisWorkbook.Charts as well if you need them.
  • Sizing in pixels. Values are points. A chart set to 800 wide, meant as pixels, comes out far larger than intended on most screens. Convert with 72 points per inch, or simply borrow sizes from cells.
  • Relying on ChartObjects(1). The index follows the order in which charts were created and changes when one is deleted. Symptom: the macro formats the wrong chart. Name the frames, then refer to them by name.
  • Running a build macro twice. Every run of a macro that creates charts adds new frames on top of the old ones. Symptom: charts look darker or bolder because two identical ones are stacked. Delete the old frames first, as lesson 2 shows.
  • Renaming charts that other code depends on. If a different macro refers to "Chart 3", renaming breaks it. Search the project with Ctrl+F for ChartObjects(" before you run the tidy macro on an old workbook.

Quick reference: objects, properties and shortcuts

The members this lesson used, sorted by the object they belong to.

ItemBelongs toWhat it does
ws.ChartObjectsWorksheetAll chart frames on the sheet
ws.ChartObjects.Add(Left, Top, Width, Height)WorksheetCreates a new frame with an empty chart
co.Left, co.Top, co.Width, co.HeightChartObjectPosition and size in points
co.NameChartObjectName shown in the Name Box and Selection Pane
co.Chart / ch.ParentChartObject / ChartFrom frame to picture / back again
ch.SetSourceData Source:=rangeChartFeeds the chart with data
ch.ChartTypeChartxlColumnClustered 51, xlLine 4
ch.SeriesCollection.CountChartNumber of series
ch.HasTitle, ch.ChartTitle.TextChartSwitch the title on, set its text
ThisWorkbook.ChartsWorkbookChart sheets, which have no frame
Alt+F11, F5, Alt+F8Excel / VBA editorEditor, run, macro list
Ctrl+G, Alt+F10VBA editor / ExcelImmediate window / Selection Pane

Real-world uses

  • Monthly management pack. A controller runs one macro after pasting new figures, and every chart in a twelve-tab workbook snaps to the same size and position before it is printed to PDF.
  • Cleaning up an inherited dashboard. An analyst takes over a workbook where charts have drifted over the years, runs the tidy macro and gets an inventory of every chart, its type and its series count in seconds.
  • Consistent charts for slides. A sales team pastes Excel charts into presentations. With identical sizes set in code, the pasted charts line up on every slide without resizing.
  • Preparing for automation. Before a reporting macro can update charts by name, the charts need predictable names. The tidy macro gives them those names once, and later code relies on them.

What you will build in the rest of this course

This lesson is free. Lessons 2 to 7 are part of the paid course, a one-time purchase of $9.90, and each one adds a piece until a single macro produces a finished, exported chart.

Adding a Chart in Code. You create charts with the classic ChartObjects.Add and the newer Shapes.AddChart2, place them against cells instead of guessed coordinates, and remove old charts first so a macro can run twice without leaving duplicates.

Feeding the Chart with SetSourceData. You hand a chart its data, learn how PlotBy decides whether twelve months become one series or twelve, and make the source grow with the data by using a dynamic last row or an Excel Table.

Choosing the Chart Type. You switch types in one line, see why a scatter chart is the only honest choice for two numeric variables, and build a combo chart with bars for actuals and a line for the target.

Titles, Axes and the Legend. You switch on and set titles, link a title to a cell so it updates itself, fix axis scales so monthly charts stay comparable, keep column charts starting at zero, and place the legend where it helps.

Working with Series and Formatting. You add series by hand with NewSeries, set values, categories and names, colour bars and lines through the modern .Format objects, and highlight a single bar such as the best month.

Exporting a Chart as an Image. You save charts as PNG files with Chart.Export, build paths that work on Windows and Mac, size charts before export for sharp images, and export every chart in a workbook in one loop.

Summary

A chart on a worksheet is two objects: the ChartObject frame, which owns position, size and name, and the Chart inside it, which owns type, data, axes and titles. co.Chart takes you from frame to picture, ch.Parent takes you back. Write code that holds both in variables instead of relying on ActiveChart and Select, borrow positions from cells, and size everything in points, and your charts will look the same on every machine and in every month.

Now try it in the lab above: run MakeChartDemo, then TidyAllCharts, then change the anchor from H2 to D16 and the height from 260 to 200. Before you run it again, work out where the second chart will start.

Frequently asked questions

What is the difference between ChartObject and Chart in Excel VBA?

A ChartObject is the frame on the worksheet with position, size and name. The Chart is the content inside it with type, series, axes and title. Use co.Chart to get from the frame to the chart.

How do I loop through all charts in a workbook with VBA?

Loop For Each ws In ThisWorkbook.Worksheets and inside it For Each co In ws.ChartObjects. Charts on their own chart sheets are in ThisWorkbook.Charts and need a separate loop.

Why does ActiveChart give run-time error 91?

ActiveChart is Nothing when no chart is selected, for example after clicking a button. Set a variable to the chart instead, such as Set ch = ws.ChartObjects(1).Chart.

What units are chart Width and Height in VBA?

Points. There are 72 points to an inch, so a chart 440 points wide is about 6.1 inches, independent of screen resolution.

How do I position a chart at a specific cell with VBA?

Read the cell position and assign it to the frame, for example co.Left = ws.Range("H2").Left and co.Top = ws.Range("H2").Top.

How do I rename a chart in Excel VBA?

Set the Name property of the ChartObject, for example ws.ChartObjects(1).Name = "chtRevenue". The new name appears in the Name Box and Selection Pane and can be used in code.

Keep going: Charts with VBA

This free lab is lesson 1 of 7. Unlock the other 6 hands-on labs, the final exam and your certificate for a one-time $9.90.

  1. Adding a Chart in Code
  2. Feeding the Chart with SetSourceData
  3. Choosing the Chart Type
  4. Titles, Axes and the Legend
  5. Working with Series and Formatting
  6. Exporting a Chart as an Image

Buy course — $9.90 See the full course

Knowledge check

A macro holds a ChartObject in a variable called co. Which of these lines raises error 438, "Object doesn't support this property or method"?

Continues in this course
  • Adding a Chart in Code
  • Feeding the Chart with SetSourceData
  • Choosing the Chart Type
  • Titles, Axes and the Legend
  • Working with Series and Formatting
  • Exporting a Chart as an Image

Buy the course to unlock the remaining 6 lessons, the exam and the certificate.

Buy course — $9.90