Ultimate Guide - Vba For Charts - Graphs in Excel (100+ Examples)
Ultimate Guide - Vba For Charts - Graphs in Excel (100+ Examples)
AWARDS
Get our FREE VBA eBook of the 30 most useful Excel VBA macros.
Microsoft MVP:
Automate Excel so that you can save time and stop doing the jobs a trained monkey could
do.
WHERE TO FIND ME
YouTube:
Ultimate Guide: VBA for Charts & Graphs in Excel Excel Off The Grid
Twitter:
Follow @exceloffthegrid
BOOKS
Tell me more…
RECENT POSTS
ActiveWorkbook.Sheets("Sheet1").Range("A1").Interior.Color = RGB(255, 0, 0)
Charts are also part of the DOM and follow similar hierarchical principles. To change the height of Chart 1, on
Sheet1, we could use the following.
Each item in the object hierarchy must be listed and separated by a period ( . ).
Knowing the document object model is the key to success with VBA charts. Therefore, we need to know the
correct order inside the object model. While the following code may look acceptable, it will not work.
In the DOM, the ActiveWorkbook does not contain ChartObjects, so Excel cannot find Chart 1. The parent of a
ChartObject is a Sheet, and the Parent of a Sheet is a Workbook. We must include the Sheet in the hierarchy
for Excel to know what you want to do.
With this knowledge, we can refer to any element of any chart using Excel’s DOM.
This may seem confusing initially, but there are good reasons for this.
To change the chart title text, we would reference the two types of chart differently:
Chart on a worksheet:
Sheets(“Sheet1”).ChartObjects(“Chart 1”).Chart.ChartTitle.Text = “My Chart Title”
Chart sheet:
Sheets(“Chart 1”).ChartTitle.Text = “My Chart Title”
The sections in bold are exactly the same. This shows that once we have got inside the Chart, the DOM is the
same.
Now we can write VBA code for a Chart sheet or a chart inside a ChartObject by referring to the Chart using
cht:
OK, so now we’ve established how to reference charts and briefly covered how the DOM works. It is time to
look at lots of code examples.
Sub CreateChart()
'Declare variables
Dim rng As Range
Dim cht As Object
End Sub
Active Chart
If there are multiple charts on a worksheet, they can be referenced by their number:
Next chtObj
If we only want to loop through the selected ChartObjects we can use the following code.
This code is tricky to apply as Excel operates differently when one chart is selected, compared to multiple
charts. Therefore, as a way to apply the Chart settings, without the need to repeat a lot of code, I recommend
calling another macro and passing the Chart as an argument to that macro.
Call AnotherMacro(ActiveChart)
Else
For Each obj In Selection
Call AnotherMacro(obj.Chart)
End If
Next
End If
Active Chart
Note: this is the same code as when referencing the active chart on the worksheet.
The following code will loop through all the chart sheets in the active workbook.
Call AnotherMacro(cht)
Next cht
All codes start with cht., as they assume a chart has been referenced using the codes above.
cht.Parent.Delete
cht.Delete
End If
Chart Axis
Charts have four axis:
xlValue
xlValue, xlSecondary
xlCategory
xlCategory, xlSecondary
These are used interchangeably in the examples below. To adapt the code to your specific requirements, you
need to change the chart axis which is referenced in the brackets.
All codes start with cht., as they assume a chart has been referenced using the codes earlier in this post.
'Display axis
cht.HasAxis(xlCategory) = True
'Hide axis
cht.HasAxis(xlValue, xlSecondary) = False
Gridlines
Gridlines help a user to see the relative position of an item compared to the axis.
'Add gridlines
cht.SetElement (msoElementPrimaryValueGridLinesMajor)
cht.SetElement (msoElementPrimaryCategoryGridLinesMajor)
cht.SetElement (msoElementPrimaryValueGridLinesMinorMajor)
cht.SetElement (msoElementPrimaryCategoryGridLinesMinorMajor)
'Delete gridlines
cht.Axes(xlValue).MajorGridlines.Delete
cht.Axes(xlValue).MinorGridlines.Delete
cht.Axes(xlCategory).MajorGridlines.Delete
cht.Axes(xlCategory).MinorGridlines.Delete
Chart Title
The chart title is the text at the top of the chart.
All codes start with cht., as they assume a chart has been referenced using the codes earlier in this post.
Chart Legend
The chart legend provides a color key to identify each series in the chart.
Plot Area
The Plot Area is the main body of the chart which contains the lines, bars, areas, bubbles, etc.
All codes start with cht., as they assume a chart has been referenced using the codes earlier in this post.
'Set the size and position of the PlotArea. Top and Left are relative to
the Chart Area.
cht.PlotArea.Left = 20
cht.PlotArea.Top = 20
cht.PlotArea.Width = 200
cht.PlotArea.Height = 150
Chart series
Chart series are the individual lines, bars, areas for each category.
All codes starting with srs. assume a chart’s series has been assigned to a variable.
Next srs
Formatting markers
Data labels
Data labels display additional information (such as the value, or series name) to a data point in a chart series.
All codes starting with srs. assume a chart’s series has been assigned to a variable.
Error Bars
Error bars were originally intended to show variation (e.g. min/max values) in a value. However, they also
commonly used in advanced chart techniques to create additional visual elements.
All codes starting with srs. assume a chart’s series has been assigned to a variable.
Data points
Each data point on a chart series is known as a Point.
Next pnt
Points have similar properties to Series, but the properties are applied to a single data point in the series
rather than the whole series. See a few examples below, just to give you the idea.
Sub FitChartToRange()
'Declare variables
Dim cht As Chart
Dim rng As Range
End Sub
Sub ExportSingleChartAsImage()
imagePath = "C:\Users\marks\Documents\myImage.png"
Set cht = ActiveChart
'Export the chart
cht.Export (imagePath)
End Sub
Sub ResizeAllCharts()
chtObj.Height = chtHeight
chtObj.Width = chtWidth
Next chtObj
End Sub
This isn’t necessarily the most efficient way to write the code, but it is to demonstrate that by understanding
the code above we can create a lot of charts.
Sub CreateBulletChart()
srs.ErrorBar Direction:=xlX, _
Include:=xlMinusValues, _
Type:=xlPercent, _
Amount:=100
'Change color of error bars
srs.ErrorBars.Format.Line.ForeColor.RGB = RGB(0, 0, 0)
srs.ErrorBar Direction:=xlX, _
Include:=xlNone, _
Type:=xlErrorBarTypeCustom
srs.ErrorBar Direction:=xlY, _
Include:=xlBoth, _
Type:=xlFixedValue, _
Amount:=0.45
'Hide axis
cht.HasAxis(xlValue, xlSecondary) = False
End Sub
Using the Macro Recorder for VBA for charts and graphs
The Macro Recorder is one of the most useful tools for writing VBA for Excel charts. The DOM is so vast that it
can be challenging to know how to refer to a specific object, property or method. Studying the code produced
by the Macro Recorder will provide the parts of the DOM which you don’t know.
As a note, the Macro Recorder creates poorly constructed code; it selects each object before manipulating it
(this is what you did with the mouse after all). But this is OK for us. Once we understand the DOM, we can
take just the parts of the code we need and ensure we put them into the right part of the hierarchy.
Conclusion
As you’ve seen in this post, the Document Object Model for charts and graphs in Excel is vast (and we’ve only
scratched the surface.
I hope that through all the examples in this post you have a better understanding of VBA for charts and graphs
in Excel. With this knowledge, I’m sure you will be able to automate your chart creation and modification.
Have I missed any useful codes? If so, put them in the comments.
Looking for other detailed VBA guides? Check out these posts:
My parents tell me that at the age of 7 I declared I was going to become a qualified
accountant. I was either psychic or had no imagination, as that is exactly what
happened. However, it wasn't until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children
during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a
small number of simple tools, I could combine them together in different ways to automate nearly all my
regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to
other professionals in our training program so they too can spend less time at work (and more time with their
children and doing the things they love).
I'm guessing the examples in this post don't exactly match your situation. We all use Excel differently, so it's
impossible to write a post that will meet everybody's needs. By taking the time to understand the techniques
and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by
discovering your own solutions.
2. Ask the 'Excel Ninja' in your office. It's amazing what things other people know.
3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people
on these forums are generally giving their time for free. So take care to craft your question, make sure
it's clear and concise. List all the things you've tried, and provide screenshots, code segments and
example workbooks.
4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel
problems.
What next?
Don't go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
How to FILTER by a list in Excel number formats for How to expand columns How to run Excel macros
Excel (including multiple accounting & finance you dynamically in Power from Power Automate
lists) NEED to know Query Desktop
How To Create Sheets For Power Query: Get data How to create QR codes in Move data between
Each Item In PivotTable when sheet/Table names Excel for FREE (3 easy workbooks (Power
Field change (2 ways) ways) Automate+Office Scripts)
How to filter by a list in How to run any macro from How to get data from Automatic commentary
Power Query (4 methods) one button (magic macro) SharePoint List with Power writing formula in Excel –
Query Amazing LAMBDA
← Power Query: Lookup value in another table with How to split cells in Excel: 4 simple ways →
merge
2 thoughts on “Ultimate Guide: VBA for Charts & Graphs in Excel (100+
examples)”
Jakob says:
Thank You
Leave a Reply
Your email address will not be published. Required fields are marked *
Comment *
Name *
Email *
Website
Post Comment
Theme by Out the Box Home Blog Newsletter Books Training Academy About Terms and conditions Privacy policy Affiliate disclosure Contact