Sub topic 16
Creating Charts with VBA
This chapter shows how to build the column and pie charts from earlier chapters with a macro. It assumes you can already insert a chart by hand, know what series and categories are, and can open the VBA editor with Alt+F11. VBA (Visual Basic for Applications) is the macro language built into Excel.
Why automate chart creation
A macro helps when you build the same chart often, such as a weekly report. It applies the same size, type, and title every time. The macro uses the same rules as the manual steps. Excel reads the source range, treats the first column as categories, and treats the other columns as series.
The data
Both macros read this range on the active sheet, in A1:B5.
Region Sales
North 120
South 95
East 140
West 80The header row names the series. The Region column supplies the categories. This is the layout from the data-preparation chapter.
The objects involved
Charts in VBA come from two objects.
- A
ChartObjectis the frame that sits on the worksheet. It has a position and a size. - Its
Chartproperty is the chart inside that frame. You set the data source, type, and title on this object.
ChartObjects.Add takes Left, Top, Width, and Height, all in points. A point is 1/72 of an inch.
A 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 SubSetSourceData is the macro version of selecting a range before you insert a chart. ChartType picks the chart type. HasTitle must be True before you set ChartTitle.Text. If you skip it, the title object does not exist and Excel raises an error.
A pie chart
Only a few lines change for 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 SubThe Top value is 320 so the pie sits below the column chart and does not cover it. ApplyDataLabels adds labels to the slices.
How the pieces fit
Common errors
- Running the macro twice stacks a second chart on top of the first. Delete the old chart first, or give each chart a different
LeftandTop. - Setting
ChartTitle.TextwithoutHasTitle = Trueraises a runtime error. - A range with blank cells or text in the value column gives wrong or empty series. Check the layout before you run the macro.
ActiveSheetmeans the macro charts whatever sheet is in front. Name the sheet, for exampleWorksheets("Data"), if the macro should always use one sheet.
Exercise
You run CreateColumnChart and get a runtime error on the line that sets ChartTitle.Text. The chart was created. What is the likely cause, and how do you fix it?
Show answer
The chart has no title object yet. Set .HasTitle = True before assigning .ChartTitle.Text, as in the example macro.
Exercise
Change CreatePieChart so it makes a bar chart of the same range, placed at Left 100 and Top 600. Which lines change?
Show answer
Change the Add call to Left:=100, Top:=600. Change .ChartType = xlPie to .ChartType = xlBarClustered. Remove .ApplyDataLabels if you do not want labels, and update the title text.