VBA Code For Charts and Graphs in Excel - Excel Off The Grid
VBA Code For Charts and Graphs in Excel - Excel Off The Grid
This post may contain af liate links. Please read my disclosure for more info. CLAIM YOUR FREE DOWNLOAD TODAY
Charts and graphs in Excel have hundreds of different options. This is great for creating precisely the visualization we want but
can be time-consuming to apply. When we want to apply those hundreds of settings to lots of charts, it can take hours and
hours of frustrating clicking. The short code snippets below will help you apply some of the most common chart options with
VBA (and hopefully turn those hours into minutes).
But don’t let me fool you into thinking that using VBA is quick and easy, it’s not. But once you’ve mastered it, you’ll know the
situations when VBA is the best option.
While it might be tempting to skip straight to the section you need, I recommend you read the rst section in full.
Understanding Excel’s Document Object Model (DOM) is essential to understand how VBA can be used with charts.
In Excel 2013, many changes were introduced to the charting engine and DOM. For example, the AddChart2 method
replaced the AddChart method. As a result, some of the code presented in this post may not work with versions before
Excel 2013.
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 ( . ).
While the following code may look acceptable, it will not work.
In the DOM, the ActiveWorkbook does not contain ChartObjects, so Excel cannot nd Chart 1. The parent of a ChartObject is
a Sheet, and the Parent of a Sheet is a Workbook. We must include the Sheet into 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.
On the worksheet itself, we nd, what VBA refers to as a ChartObject. Within each ChartObject is a Chart. Effectively FOLLOW ME ON SOCIAL MEDIA
a ChartObject is a container which holds a Chart.
Follow @exceloffthegrid
A Chart is also a stand-alone sheet; it does not have a ChartObject around it.
To change the chart title text, we would reference the two types of chart differently:
Chart on a worksheet:
Chart sheet:
The sections in bold are the same, which shows that once we have got inside the Chart, the DOM is the same.
We want to write code which will work on any chart; we do this by creating a variable which holds the reference to a Chart.
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 brie y covered how the DOM works. It is time to look at lots of
code examples.
If there are multiple charts on a worksheet, they can be referenced by their number. 1 = the rst chart created, 2 = the second
chart created etc, etc.
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
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
Chart
Some basic chart settings are shown below:
cht.Parent.Delete
cht.Delete
End If
Chart Axis
There are four chart axis:
xlValue
xlValue, xlSecondary
xlCategory
xlCategory, xlSecondary
These are used interchangeably in the examples below. To adapt the code to your speci c requirements you need to change the
value in the brackets.
'Display axis
cht.HasAxis(xlCategory) = True
'Hide axis
cht.HasAxis(xlValue, xlSecondary) = False
Gridlines
'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).MajorGridli.Delete
cht.Axes(xlCategory).MinorGridlines.Delete
Chart Title
Chart Legend
Plot Area
Chart series
Set up a Series variable to hold a chart series. 1 = First chart series, 2 = Second chart series.
Next srs
Series formatting
Error Bars
Points
Each data point on a chart series is known as a Point.
Next pnt
Point Codes
Points have similar properties to Series, but it is 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 CreateBulletChart()
srs.ErrorBar Direction:=xlX, _
Include:=xlMinusValues, _
Type:=xlPercent, _
Amount:=100
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
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.
← Loop through each item in a Data Validation list with VBA Resize a UserForm with VBA or Windows API →
ramprakash says:
While updating the color for graph we are getting following error
Run time error ‘1004’
parameter not valid
Dim Cht1 As Chart
Set Cht1 = ActiveSheet.ChartObjects(“Chart 1”).Chart
Cht1.ChartArea.Select
Cht1.FullSeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
Cht1.ChartArea.Select
Cht1.FullSeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
Cht1.ChartArea.Select
Cht1.FullSeriesCollection(3).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
Cht1.FullSeriesCollection(4).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
Hi Ramprakash – the VBA code above is applied to the Series 1, 2, 3 and 4, but you probably have
less than 4 series in the chart.
Also, you don’t need to use the Cht1.ChartArea.Select lines, they don’t achieve anything.
pablo says:
Leave a Reply
Your email address will not be published. Required elds are marked *
Comment
Name *
Email *
Website
Post Comment
Theme by Out the Box Home Consultancy Terms and conditions Privacy policy Af liate disclosure Contact