Sub topic 16
Creating charts with VBA
This chapter assumes you can open the Visual Basic Editor (Alt+F11), insert a module, and run a macro. It also assumes you know how series, categories, and chart types work from the earlier chapters. Here you will turn the manual steps (select a range, insert a chart, set the type, add a title) into code you can repeat.
How VBA sees a chart
A chart on a worksheet is two objects. A ChartObject is the frame that sits on the sheet and has a position and a size. Its Chart property is the chart itself, which holds the type, series, title, and axes.
Position and size (Left, Top, Width, Height, Name) belong to the ChartObject. Everything you would format from the Chart Design tab belongs to the Chart.
A first macro and what each line does
Use the sample range from the earlier chapters, with a header row in A1:B1 and four regions below it:
Region Sales
North 120
South 95
East 140
West 80This macro embeds a clustered column chart:
Sub CreateColumnChart()
Dim co As ChartObject
Set co = ActiveSheet.ChartObjects.Add(Left:=100, Top:=50, Width:=400, Height:=250)
With co.Chart
.SetSourceData Source:=ActiveSheet.Range("A1:B5")
.ChartType = xlColumnClustered
.HasTitle = True
.ChartTitle.Text = "Sales by Region"
End With
End SubChartObjects.Addcreates an empty frame. Its four arguments are in points, not cells.SetSourceDatadoes what selecting a range before Insert does. Excel applies its usual rules: text in the first column becomes categories, and numbers become series.ChartTypetakes anXlconstant. The ones used in this tutorial arexlColumnClustered,xlBarClustered,xlLineMarkers, andxlPie.HasTitlemust beTruebefore you setChartTitle.Text. Otherwise the title object does not exist and Excel raises an error.
Only the chart type changes between a column chart and a pie chart:
Sub CreatePieChart()
Dim co As ChartObject
Set co = ActiveSheet.ChartObjects.Add(Left:=100, Top:=320, Width:=300, Height:=250)
With co.Chart
.SetSourceData Source:=ActiveSheet.Range("A1:B5")
.ChartType = xlPie
.HasTitle = True
.ChartTitle.Text = "Share of Sales by Region"
.ApplyDataLabels
End With
End SubMaking the macro repeatable
The macros above have two weaknesses. They depend on whichever sheet is active, and every run adds another chart on top of the last one. A reusable version names the sheet, names the chart, and deletes any earlier chart of the same name:
Sub BuildSalesChart(ByVal chartKind As XlChartType, ByVal chartName As String, _
ByVal chartCaption As String, ByVal anchorCell As String)
Dim ws As Worksheet
Dim co As ChartObject
Set ws = ThisWorkbook.Worksheets("Sheet1")
On Error Resume Next
ws.ChartObjects(chartName).Delete
On Error GoTo 0
Set co = ws.ChartObjects.Add( _
Left:=ws.Range(anchorCell).Left, _
Top:=ws.Range(anchorCell).Top, _
Width:=360, Height:=220)
co.Name = chartName
With co.Chart
.SetSourceData Source:=ws.Range("A1:B5"), PlotBy:=xlColumns
.ChartType = chartKind
.HasTitle = True
.ChartTitle.Text = chartCaption
End With
End Sub
Sub BuildAllCharts()
BuildSalesChart xlColumnClustered, "chtSalesColumn", "Sales by Region", "D2"
BuildSalesChart xlBarClustered, "chtSalesBar", "Sales by Region (bar)", "D18"
BuildSalesChart xlPie, "chtSalesPie", "Share of Sales by Region", "N2"
End SubThree details matter here:
ThisWorkbookis the workbook that contains the macro.ActiveWorkbookis whichever workbook the user last clicked, which may not be the one you meant.PlotBy:=xlColumnstells Excel that each column is a series. UsexlRowswhen your series run across rows.On Error Resume Nextis limited to the single delete line and switched off immediately. Referring to a chart name that does not exist raises error 9 ("Subscript out of range"), and here that is the expected case on the first run.
Charts that follow an Excel Table
A chart built on an Excel Table range grows when you add rows to the table. In VBA you pass the table's Range property. First create the sample data. Add a worksheet named Trend, then run this once:
Sub PrepareTrendData()
Dim ws As Worksheet
Dim lo As ListObject
Set ws = ThisWorkbook.Worksheets("Trend")
ws.Range("A1:B1").Value = Array("Month", "Units")
ws.Range("A2:A5").Value = Application.Transpose(Array("Jan", "Feb", "Mar", "Apr"))
ws.Range("B2:B5").Value = Application.Transpose(Array(30, 42, 38, 51))
Set lo = ws.ListObjects.Add(xlSrcRange, ws.Range("A1:B5"), , xlYes)
lo.Name = "tblMonthly"
End SubNow build a line chart from the table and label its value axis:
Sub CreateLineFromTable()
Dim ws As Worksheet
Dim lo As ListObject
Dim co As ChartObject
Set ws = ThisWorkbook.Worksheets("Trend")
Set lo = ws.ListObjects("tblMonthly")
Set co = ws.ChartObjects.Add(Left:=ws.Range("D2").Left, _
Top:=ws.Range("D2").Top, _
Width:=380, Height:=230)
co.Name = "chtMonthlyUnits"
With co.Chart
.SetSourceData Source:=lo.Range
.ChartType = xlLineMarkers
.HasTitle = True
.ChartTitle.Text = "Units per Month"
.HasLegend = False
.Axes(xlValue).HasTitle = True
.Axes(xlValue).AxisTitle.Text = "Units"
End With
End SubType May and 47 in the first empty row under the table. The table expands and the line gains a fifth point without any code running.
Controlling series directly
SetSourceData guesses the layout. When the guess is wrong, or the data is not contiguous, build the series yourself:
Sub CreateColumnWithExplicitSeries()
Dim ws As Worksheet
Dim co As ChartObject
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set co = ws.ChartObjects.Add(Left:=ws.Range("D34").Left, _
Top:=ws.Range("D34").Top, _
Width:=360, Height:=220)
With co.Chart
.ChartType = xlColumnClustered
With .SeriesCollection.NewSeries
.Name = "=Sheet1!$B$1"
.XValues = "=Sheet1!$A$2:$A$5"
.Values = "=Sheet1!$B$2:$B$5"
End With
End With
End SubThis maps to the Select Data dialog. Name is the series name, XValues holds the category labels, and Values holds the numbers. Each is a reference string that begins with =.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Regions appear as separate series | Excel guessed rows instead of columns | Pass `PlotBy:=xlColumns` to `SetSourceData` |
| Run-time error 1004 on `ChartTitle` | `HasTitle` was not set to `True` first | Set `HasTitle` before `ChartTitle.Text` |
| Chart lands on the wrong sheet | Code relied on `ActiveSheet` | Use `ThisWorkbook.Worksheets("Name")` |
| Duplicate charts after each run | New object added every time | Name the chart and delete the old one first |
| Pie shows only one series | Pie charts plot only the first series | Pass one value column to the pie |
| Macro vanishes after saving | File saved as `.xlsx` | Save as `.xlsm` |
Choosing an approach
Use the short recorded-style macro for a one-off chart. Use the named, parameterized version when you build the same chart on a schedule or for several sheets. Use explicit NewSeries code when the source range is non-contiguous or needs custom names. Use a table-backed chart when the data grows, because Excel then handles the resizing and your code does not have to.
Exercise
You run CreateColumnChart three times and see three stacked charts. Which two changes to the macro stop this?
Show answer
Give the chart a name (co.Name = "chtSales") and delete any existing chart with that name before calling ChartObjects.Add, for example with On Error Resume Next, ActiveSheet.ChartObjects("chtSales").Delete, then On Error GoTo 0. Naming makes the old chart findable, and deleting it prevents duplicates.
Exercise
A macro calls .SetSourceData Source:=ws.Range("A1:C5") and the chart shows the months (in row 1) as series instead of the three products. Which argument fixes it, and what value does it take?
Show answer
Add PlotBy:=xlColumns. This makes each column a series, so the three product columns become series and the first column supplies the category labels. Use xlRows for the opposite layout.