Quick VBA Routine: XY Chart with Axis Titles
by Jon Peltier
Peltier Technical Services, Inc., Copyright © 2009.
Licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
Someone asked in the newsgroup how to create an XY chart in Excel that uses the label at the top of the columns of X and Y data for the axis titles. That’s not built in, but it’s not hard to do if you know a little VBA. I’ve taken an example from my web site, Interactive Chart Creation, and embellished it a bit.
The VBA procedure (code below) actually works a bit like my first recollection of Excel charting, which had two dialogs, one asking for the data range, the other asking for the range of cells to cover witth the chart. Since I always align my charts with the cell boundaries, this is nicer than the Chart Wizard in Excel versions up to 2003 and the Insert Chart command in Excel 2007.
The code uses a couple of input boxes to get the ranges from the user. I’ve added some smarts so it uses the selection as the default for the source data range in the first input box. If the selection is a single cell, the macro uses the cell’s current region (the contiguous range including the cell).
Copy the code below (use the plain text view of the code for copying) into a regular module in the VB Editor, then from Excel’s Tools menu, choose Macro, then Macros, or use the Alt+F8 shortcut key combination, then select and run the macro ChartWithAxisTitles.

The first input box asks you to select the data range. Note that the active cell C9 has been expanded to its current region B2:D21 for the dialog’s default data range.

The second input box asks you to select a region for the chart to cover.

The result is an XY chart with default chart and series formatting. I’ve cleaned up the formatting slightly here, after the procedure inserted the chart, but obviously there’s room for improvement, particularly with the spacing of the chart elements.

My data range had three columns. The first is used for X values and the X axis title, the others are used for Y values for two series. The cell above the first Y data column is used for the Y axis title, and the cell above each Y data column is used for the corresponding series name.
Here is the minimally documented code:
Sub ChartWithAxisTitles() Dim objChart As ChartObject Dim myChtRange As Range Dim myDataRange As Range Dim myInitialRange As Range Dim sInitialRange As String ' bail out if we're not on a worksheet If Not ActiveSheet Is Nothing Then If TypeName(ActiveSheet) = "Worksheet" Then ' propose an initial data range If TypeName(Selection) = "Range" Then Set myInitialRange = Selection If myInitialRange.Cells.Count = 1 Then Set myInitialRange = myInitialRange.CurrentRegion sInitialRange = myInitialRange.Address(True, True) End If End If With ActiveSheet ' ask user for range that contains data for chart On Error Resume Next Set myDataRange = Application.InputBox( _ prompt:="Select a range containing the chart data.", _ Title:="Select Chart Data", Default:=sInitialRange, Type:=8) On Error GoTo 0 If myDataRange Is Nothing Then Exit Sub ' ask user for range chart should cover On Error Resume Next Set myChtRange = Application.InputBox( _ prompt:="Select a range where the chart should appear.", _ Title:="Select Chart Position", Type:=8) On Error GoTo 0 If myChtRange Is Nothing Then Exit Sub ' cover chart range with chart Set objChart = .ChartObjects.Add( _ Left:=myChtRange.Left, Top:=myChtRange.Top, _ Width:=myChtRange.Width, Height:=myChtRange.Height) ' Put all the right stuff in the chart With objChart.Chart .ChartArea.AutoScaleFont = False .ChartType = xlXYScatterLines .SetSourceData Source:=myDataRange, PlotBy:=xlColumns .HasTitle = True .ChartTitle.Characters.Text = "My Title" .ChartTitle.Font.Bold = True .ChartTitle.Font.Size = 10 With .Axes(xlCategory, xlPrimary) .HasTitle = True With .AxisTitle .Font.Size = 8 .Font.Bold = True .Characters.Text = myDataRange.Cells(1, 1) End With End With With .Axes(xlValue, xlPrimary) .HasTitle = True With .AxisTitle .Font.Size = 8 .Font.Bold = True .Characters.Text = myDataRange.Cells(1, 2) End With End With End With End With End If End If End Sub
Possibly Related Posts:
- UDF to Calculate an Arbitrary Formula
- Display One Chart Dynamically and Interactively
- Link Chart Text to a Cell
- Label Each Series in a Chart
- Label Last Point for Excel 2007
- Physics Lesson
- How To: Fix a Recorded Macro
- Order of Points in XY and Line Charts
- VBA to Split Data Range into Multiple Chart Series
- VBA to Filter Chart Data Range
Posted: Thursday, March 6th, 2008 under VBA.
Comments: 4
Comments
Pingback from Quick VBA Routine: XY Chart with Axis Titles | Quick Work
Time: Thursday, March 6, 2008, 1:48 am
[...] admin wrote an interesting post today onHere’s a quick excerptSomeone asked in the newsgroup how to create an XY chart in Excel that uses the label at the top of the columns of X and Y data for the axis titles. That’s not built in, but it’s not hard to do if you know a little VBA. … [...]
Comment from Matt
Time: Tuesday, December 9, 2008, 2:00 am
I have just started running into a problem where a selected range is not recognised as a range and so I get spat out on through the isrange…exit sub checks (2003, XP sp2). Has anyone else had this occur and know a solution?
Thanks
Matt
Comment from Jon Peltier
Time: Tuesday, December 9, 2008, 6:29 am
When you get this error, go to the VB Editor, open the Immediate Window (Ctrl+G), type in
?typename(selection)
then press Enter and see what the response is. If that doesn’t help, step through the code and see where you are ejected from execution.
Comment from Jon Peltier
Time: Wednesday, December 10, 2008, 7:29 am
Matt responded via email instead of posting here. He said:
If I select a range of cells then the suggested code in the immediate
window returns type Range. When I select the same range of cells when
asked for a chart range via the input box, then run the immediates
window on ? typename(myDataRange) the type of myDataRange returns type
Nothing, hence I get spat out at ‘If myDataRange is Nothing Then Exit
Sub’.
If I accept the default data range then I get spat out on the ‘If
myChtRange Is Nothing Then Exit Sub’ as this input box again returns
type nothing.
I have just changed PCs (supposedly within the same standard operating
environment) - are there any VBA references that should be set by
default?
Matt -
After the Set MyDataRange = statement, insert this code:
MsgBox "MyDataRange is type " & TypeName(MyDataRange" _
& vbNewLine & "Error " & Err.Number & ": " & Err.Description
Similarly, after the Set MyChtRange = statement, insert this code:
MsgBox "MyDataRange is type " & TypeName(MyChtRange" _
& vbNewLine & "Error " & Err.Number & ": " & Err.Description
Then rerun the code, once accepting the default data range, once setting your own, and email me screen shots of the message boxes.























Write a comment
I welcome comments from my readers. If you have an opinion on this post, if you have a question or if there is anything to add, I want to hear from you. Whether you agree or disagree, please join the discussion.
If you want to include an image in your comment, post it on your own site or on one of the many free image sharing sites, and include a link in your comment. I'll download your image and insert the necessary html to display the image inline.
Read the PTS Blog Comment Policy.