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.
| Row | A: Month | B: Revenue | Formula behind it |
|---|---|---|---|
| 2 | Jan | 1,274 | 1000 + 2 * 137 |
| 3 | Feb | 1,411 | 1000 + 3 * 137 |
| 4 | Mar | 1,548 | 1000 + 4 * 137 |
| 5 | Apr | 1,685 | 1000 + 5 * 137 |
| 6 | May | 1,822 | 1000 + 6 * 137 |
| 7 | Jun | 1,959 | 1000 + 7 * 137 |
| 8 | Jul | 2,096 | 1000 + 8 * 137 |
| 9 | Aug | 2,233 | 1000 + 9 * 137 |
| 10 | Sep | 2,370 | 1000 + 10 * 137 |
| 11 | Oct | 2,507 | 1000 + 11 * 137 |
| 12 | Nov | 2,644 | 1000 + 12 * 137 |
| 13 | Dec | 2,781 | 1000 + 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.
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.
| Chart | Name | Left | Top | Width | Height | ChartType |
|---|---|---|---|---|---|---|
| 1 before | Chart 1 (Excel default) | 200 | 20 | 300 | 180 | 51 (xlColumnClustered) |
| 2 before | Chart 2 (Excel default) | 260 | 90 | 250 | 150 | 4 (xlLine) |
| 1 after | cht02_01 (for example) | ≈ 336 | ≈ 15 | 440 | 260 | 51, unchanged |
| 2 after | cht02_02 (for example) | ≈ 336 | ≈ 295 | 440 | 260 | 4, 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.
Line by line: what each part does
For Each co In ws.ChartObjectsloops through the frames on one worksheet. Charts on chart sheets are not in this collection.Set ch = co.Chartis the bridge from frame to picture. Everything that sets position and size usesco, everything that reads content usesch.co.Name = "cht" & Format(ws.Index, "00") & "_" & Format(n, "00")gives a stable name. Later code can sayws.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.Leftborrows the position of cell H2. EveryRangehasLeft,Top,WidthandHeightin points, so cells make perfect anchors.(n - 1) * 280places 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 = 440andco.Height = 260are 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.ChartTypeprints as a number, because chart type constants are numbers: 51 for a clustered column, 4 for a line.ch.SeriesCollection.Countis 1 for both demo charts.Debug.Printwrites one line per chart to the Immediate window. TheMsgBoxonly 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
- Open a new workbook and save it as Excel Macro-Enabled Workbook (*.xlsm) with
F12. - Press
Alt+F11(Mac:Opt+F11) to open the VBA editor, select your workbook in the Project Explorer and choose Insert → Module. - Paste
MakeChartDemoandTidyAllChartsfrom the lab into the module, with oneOption Explicitat the top. - Click inside
MakeChartDemoand pressF5. A new sheet named Chart Demo plus a time stamp appears, with data in A1:B13 and two overlapping charts. - 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
Escto deselect. - Press
Alt+F8, chooseTidyAllChartsand click Run. The message box reports how many charts were aligned. - Return to the editor and press
Ctrl+G. The Immediate window lists each chart with its new name, type and series count. - 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.
Alt+F10 on Windows. It is the quickest way to confirm the names your macro gave.
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 = xlLineorch.Left = 100both 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.ChartObjectsnever 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 overThisWorkbook.Chartsas 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 withCtrl+FforChartObjects("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.
| Item | Belongs to | What it does |
|---|---|---|
ws.ChartObjects | Worksheet | All chart frames on the sheet |
ws.ChartObjects.Add(Left, Top, Width, Height) | Worksheet | Creates a new frame with an empty chart |
co.Left, co.Top, co.Width, co.Height | ChartObject | Position and size in points |
co.Name | ChartObject | Name shown in the Name Box and Selection Pane |
co.Chart / ch.Parent | ChartObject / Chart | From frame to picture / back again |
ch.SetSourceData Source:=range | Chart | Feeds the chart with data |
ch.ChartType | Chart | xlColumnClustered 51, xlLine 4 |
ch.SeriesCollection.Count | Chart | Number of series |
ch.HasTitle, ch.ChartTitle.Text | Chart | Switch the title on, set its text |
ThisWorkbook.Charts | Workbook | Chart sheets, which have no frame |
Alt+F11, F5, Alt+F8 | Excel / VBA editor | Editor, run, macro list |
Ctrl+G, Alt+F10 | VBA editor / Excel | Immediate 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.
- 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