Sie sind auf Seite 1von 8

7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru

CHECK OUT the recently launched My First Add-in templates and start creating your own add-ins today! ×

HOME ABOUT BLOG VBA VAULT STORE CONTACT

The VBA Coding Guide For Excel Charts & Graphs


March 01, 2015 Chris Newman

Search

Just Launched!

Create Excel, PowerPoint, Word add-ins with ease with


this revolutionary template and online course!

My Favorite Add-ins & Articles!

Charts, Charts, & More Charts!


Graphical visualizations are arguably the pinnacle of how an analyst shares his/her results and possessing the ability
to manipulate them is key to the field. Since we as data analysts spend some much time creating graphs, it is more
valuable than ever to understand how to automate them.

What if you have 20 graphs on a spreadsheet and they all need to have their legends in the exact same spot? What
if you create a bunch of charts and your manager needs the series colors changed at the last minute? Do you want to
do this all manually?

Below will be your cheat sheet for manipulating Excel charts & graphs with VBA code. Please let me know via the
comments section if there are areas missing from this guide so I can expand on them. Enjoy!

Inserting A Chart
Method 1:

Sub CreateChart()
'PURPOSE: Create a chart (chart dimensions are not required)

Dim rng As Range


Dim cht As Object

'Your data range for the chart


Set rng = ActiveSheet.Range("A24:M27")

'Create a chart
Set cht = ActiveSheet.Shapes.AddChart2

'Give chart some data


cht.Chart.SetSourceData Source:=rng

'Determine the chart type


cht.Chart.ChartType = xlXYScatterLines

End Sub
Latest VBA Code Vault Posts

Method 2: Swap Two Selected Cell


Ranges In Excel
3 WEEKS AGO

Sub CreateChart()
'PURPOSE: Create a chart (chart dimensions are required)

Dim rng As Range

https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 1/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru
Dim cht As ChartObject
VBA To Only Change
'Your data range for the chart
Set rng = ActiveSheet.Range("A24:M27")
Selection's Border Color
4 MONTHS AGO
'Create a chart
Set cht = ActiveSheet.ChartObjects.Add( _
Left:=ActiveCell.Left, _
Width:=450, _
Remove Page Breaks From All
Top:=ActiveCell.Top, _ Open Spreadsheets
Height:=250)
5 MONTHS AGO
'Give chart some data
cht.Chart.SetSourceData Source:=rng

'Determine the chart type


cht.Chart.ChartType = xlXYScatterLines Free Webinars
End Sub

Looping Through Charts & Series

Sub LoopThroughCharts()
'PURPOSE: How to cycle through charts and chart series

Dim cht As ChartObject


Dim ser As Series

'Loop Through all charts on ActiveSheet


For Each cht In ActiveSheet.ChartObjects

Next cht Most Popular Blog Posts


'Loop through all series in a chart
For Each ser In grph.Chart.SeriesCollection
Easy Step-By-Step
Next ser
Instructions To Create Your
'Loop Through all series on Activesheet
For Each cht In ActiveSheet.ChartObjects
First Excel Ribbon Add-in
For Each ser In grph.Chart.SeriesCollection 4 YEARS AGO

Next ser
Next cht
The VBA Guide To Excel Pivot
End Sub Tables
5 YEARS AGO

5 Different Ways to Find The


Adding & Modifying A Chart Title Last Row or Last Column
Using VBA
5 YEARS AGO
Sub AddChartTitle()
'PURPOSE: Add a title to a specific chart

Dim cht As ChartObject Copy & Paste Multiple Excel


Set cht = ActiveSheet.ChartObjects("Chart 1")
Ranges To Separate
PowerPoint Slides With VBA
'Ensure chart has a title
cht.Chart.HasTitle = True 5 YEARS AGO

'Change chart's title


cht.Chart.ChartTitle.Text = "My Graph"

End Sub

Follow @ChrisMacro

Sub RepositionChartTitle()
'PURPOSE: Reposition a chart's title The Spreadsh…
2.2K likes
Dim cht As ChartObject

Set cht = ActiveSheet.ChartObjects("Chart 1")

'Reposition title Like Page


With cht.Chart.ChartTitle
.Left = 100
.Top = 50
Be the first of your friends to like this
End With

End Sub

Adding & Modifying A Graph Legend

Sub InsertChartLegend()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects("Chart 1").Chart

'Add Legend to the Right


cht.SetElement (msoElementLegendRight)

'Add Legend to the Left


cht.SetElement (msoElementLegendLeft)

'Add Legend to the Bottom


cht.SetElement (msoElementLegendBottom)

https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 2/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru
'Add Legend to the Top
cht.SetElement (msoElementLegendTop)

'Add Overlaying Legend to the Left


cht.SetElement (msoElementLegendLeftOverlay)

'Add Overlaying Legend to the Right


cht.SetElement (msoElementLegendRightOverlay)

End Sub

Sub DimensionChartLegend()

Dim lgd As Legend

Set lgd = ActiveSheet.ChartObjects("Chart 1").Chart.Legend

lgd.Left = 240.23
lgd.Top = 6.962
lgd.Width = 103.769
lgd.Height = 25.165

End Sub

Adding Various Chart Attributes

Sub AddStuffToChart()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects("Chart 1").Chart

'Add X-axis
cht.HasAxis(xlCategory, xlPrimary) = True '[Method #1]
cht.SetElement (msoElementPrimaryCategoryAxisShow) '[Method #2]

'Add X-axis title


cht.Axes(xlCategory, xlPrimary).HasTitle = True '[Method #1]
cht.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) '[Method #2]

'Add y-axis
cht.HasAxis(xlValue, xlPrimary) = True '[Method #1]
cht.SetElement (msoElementPrimaryValueAxisShow) '[Method #2]

'Add y-axis title


cht.Axes(xlValue, xlPrimary).HasTitle = True '[Method #1]
cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis) '[Method #2]

'Add Data Labels (Centered)


cht.SetElement (msoElementDataLabelCenter)

'Add Major Gridlines


cht.SetElement (msoElementPrimaryValueGridLinesMajor)

'Add Linear Trend Line


cht.SeriesCollection(1).Trendlines.Add Type:=xlLinear

End Sub

Modifying Various Chart Attributes

Sub ChangeChartFormatting()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects("Chart 1").Chart

'Adjust y-axis Scale


cht.Axes(xlValue).MinimumScale = 40
cht.Axes(xlValue).MaximumScale = 100

'Adjust x-axis Scale


cht.Axes(xlCategory).MinimumScale = 1
cht.Axes(xlCategory).MaximumScale = 10

'Adjust Bar Gap


cht.ChartGroups(1).GapWidth = 60

'Format Font Size


cht.ChartArea.Format.TextFrame2.TextRange.Font.Size = 12

'Format Font Type


cht.ChartArea.Format.TextFrame2.TextRange.Font.Name = "Arial"

'Make Font Bold


cht.ChartArea.Format.TextFrame2.TextRange.Font.Bold = msoTrue

'Make Font Italicized


cht.ChartArea.Format.TextFrame2.TextRange.Font.Italic = msoTrue

End Sub

Removing Various Chart Attributes

Sub RemoveChartFormatting()

https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 3/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru
Dim cht As Chart

Set cht = ActiveSheet.ChartObjects("Chart 1").Chart

'Remove Chart Series


cht.SeriesCollection(2).Delete

'Remove Gridlines
cht.Axes(xlValue).MajorGridlines.Delete
cht.Axes(xlValue).MinorGridlines.Delete

'Remove X-axis
cht.Axes(xlCategory).Delete

'Remove Y-axis
cht.Axes(xlValue).Delete

'Remove Legend
cht.Legend.Delete

'Remove Title
cht.ChartTitle.Delete

'Remove ChartArea border


cht.ChartArea.Border.LineStyle = xlNone

'No background color fill


cht.ChartArea.Format.Fill.Visible = msoFalse
cht.PlotArea.Format.Fill.Visible = msoFalse

End Sub

Change Your Colors

Sub ChangeChartColors()

Dim cht As Chart

Set cht = ActiveSheet.ChartObjects("Chart 1").Chart

'Change first bar chart series fill color


cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(91, 155, 213)

'Change X-axis label color


cht.Axes(xlCategory).TickLabels.Font.Color = RGB(91, 155, 213)

'Change Y-axis label color


cht.Axes(xlValue).TickLabels.Font.Color = RGB(91, 155, 213)

'Change Plot Area border color


cht.PlotArea.Format.Line.ForeColor.RGB = RGB(91, 155, 213)

'Change Major gridline color


cht.Axes(xlValue).MajorGridlines.Format.Line.ForeColor.RGB = RGB(91, 155, 213)

'Change Chart Title font color


cht.ChartTitle.Format.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = RGB(91, 155, 213)

'No background color fill


cht.ChartArea.Format.Fill.Visible = msoFalse
cht.PlotArea.Format.Fill.Visible = msoFalse

End Sub

More Of My Charting Articles


Automatically Extending Excel Chart Series' Ranges For Next Year

Make All Charts Plot Non-Visible Cells in Your Excel Workbook

Scroll To Chart Based on Form Control Combo Box Selection

Anything You Would Like To See?


There are a ton of things you can do with VBA and Excel charts. I attempted through this guide to tackle the most
general ones, but please don't hesitate to leave a comment if there is something that you would like to see added to
the code in this VBA guide. Hopefully, you were able to find what you were looking for!

https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 4/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru

Share This Post!

Did you find this post helpful? Do you want to support this blog because you're just that awesome?! By sharing this
post on Facebook, Twitter, or Google+ you are not only providing others with great information, you are creating
exposure for The Spreadsheet Guru website. Growing this community is my number one goal as I have found
learning to increase exponentially when lots of people are contributing to the conversation. Learning is the whole
reason why this blog exists! If you want to spread the word just click on the Share button right below this paragraph
(next to the Like button -- I enjoy "likes" too!) or on the Floating Share Bar to the left and select your preferred social
medium. Thank you so much for reading and I hope I can continue to provide you with great content in the future!
Cheers!

 26 Comments 21 Likes Share


 Excel, VBA, Guides
 Charts

 REMOVE BLANK ROWS & COLUMNS WITH ... THE BEST WAY TO IMPROVE VBA MACRO ... 

24 Comments TheSpreadsheetGuru 
1 Login

 Recommend 10 t Tweet f Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Marcelo Dreux • 8 months ago • edited


In your first example, when executing the last command, to modify the graphics type, it is removing the
horizontal names and it is transforming them to numbers, Am I doing something wrong?
△ ▽ • Reply • Share ›

Tran Dang An • a year ago


I would like to make a diagram in excel sheet. Could you help me to make a VBA. Please see diagram as
attached file.
△ ▽ • Reply • Share ›

Tran Dang An • a year ago • edited


I would like to create diagram as attached file. Could you please help?
△ ▽ • Reply • Share ›

Vibishna Balagopal • a year ago


How do we add vertical lines or dots in a chart to indicate (say) maximum value across multiple series?
△ ▽ • Reply • Share ›

Kat R • 3 years ago


I'm searching for a script that will enable me to place dynamic trendlines on multiple series in a pivot
chart, that won't disappear every time I adjust the filter parameters... any ideas?
thanks
△ ▽ • Reply • Share ›

Mr. McCarthy • 3 years ago


is it possible to create a userform to build the basis for you chart being "any kind of chart" so that the
code vba behind the user form collects the chart title and axis titles and send it straight to the chart
without referenceing a cell on the sheet?
△ ▽ • Reply • Share ›

Deepthi Kunhappan • 3 years ago


Hi Chris,

Thank you so much for all the information required for creating customized charts. I am quite new to VBA
and I learn most of this through blogs online and this is definitely a huge lesson for me! :)

The 'change your colors' section is exactly what I was looking for. But may I probe further and ask if there
is a way to set certain colors for series names in a chart? I was looking it at this option because I am
creating a dashboard from pivot tables which have a large number of products (series) and these would
repeat over in different graphs.

Could you kindly suggest how I could possibly get this?


△ ▽ • Reply • Share ›
https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 5/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru

Le • 3 years ago • edited


Is there any way to change the color of the x or y axis easily?
△ ▽ • Reply • Share ›

Edgar Mostert • 3 years ago • edited


Hi Chris, I have an issue with selecting the data. I want to update my graphs every month with running a
macro. My data is this month in the range A1:C6 with row A1:C1 as headers. Next month there will be
one row more, A7:C7 will be added, so the total field of data will be A1:C7. And the next month another
row added, and so on... Do you have code for this because I can't figure it out. Thanks a lot!
△ ▽ • Reply • Share ›

Shen Le • 3 years ago


I'm using Mac so it looks different.
I managed to change the axis but I want to create a secondary axis. So in real life it's like after plotting a
scattergraph, i want to format data series and get a secondary axis.
I also want to create a title
And move the chart down.
No idea how to do it.
Thanks
△ ▽ • Reply • Share ›

JameR • 3 years ago


I have the following problem, my chart shrinks (X axis to the left) every time I generate a new excel doc
for new vendor#. Basically, I get a list of vendors in one book using query. Some PO data going 52
weeks back on another book/sheet ( using another query) based on a vendor from the first book. Based
on the data that I retrieved, I build a chart that I copy to the third empty sheet and save for emailing. As I
cycle through the vendor list (on the first book/sheet), my chart/X axis shrinks starting from the document
# 10. The chart shrinks to the left, but area of the chart stays the same. I do not know how to fix it. Any
help, please.
△ ▽ • Reply • Share ›

B-Lo • 3 years ago


I'm looking for a way to click on a chart at any given location, then have a dialog box pop up to enter the
information of a new data point at that same mouse-click location. Is there a way to accomplish this?
△ ▽ • Reply • Share ›

Allan Martin • 3 years ago


Is there a way of using VBA to count the categories in a chart? I thought that CategoryCollection.count
might be the function but struggling to get it to work.
△ ▽ • Reply • Share ›

James • 3 years ago


Is there a way using VBA to modify the elements of a table that has been added to a chart? For example
if I wanted to change the formatting of data points within the table or remove an entire series from the
table.
△ ▽ • Reply • Share ›

Rose > James • 3 years ago


Ici j'utilise une ListBox avec une sélection multiple pour cocher ou décocher les séries à afficher :

Private Sub LbSeries_Change()


Dim LeGraphique As ChartObject
Dim NouvelleSerie As Object
Dim UneSerie As Series
Dim i As Byte
Dim SerieExiste As Boolean

Set LeGraphique = ActiveSheet.ChartObjects("GraphOK")

For i = 0 To LbSeries.ListCount - 1
SerieExiste = False
If LbSeries.Selected(i) = True Then
'vérifier ici si la série existe déjà sinon l'ajouter
For Each UneSerie In LeGraphique.Chart.SeriesCollection
If UneSerie.Name = LbSeries.List(i) Then
'MsgBox "déjà là"
SerieExiste = True
see more

△ ▽ • Reply • Share ›

Ján Žitniak • 4 years ago


Thank you for your VBA chart tutorial. It helped me a lot. Some examples don't work on my Excel 2010.
E.g. FullSeriesCollection method (I used SeriesCollection instead). Also the following code doesn't work:

'Add y-axis
cht.SetElement (msoElementPrimaryValueAxisShow)

'Add y-axis title


cht.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)

R d J
https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 6/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru
Regards Jan.
△ ▽ • Reply • Share ›

Peltier Tech > Ján Žitniak • 4 years ago


FullSeriesCollection was introduced in Excel 2013. Use SeriesCollection instead.

I don't like using the SetElement command. I prefer things like

cht.HasAxis(xlValue, xlPrimary) = True


cht.Axes(xlValue, xlPrimary).HasTitle = True
△ ▽ • Reply • Share ›

Chris Mod > Peltier Tech • 4 years ago


Thanks for the suggestions guys, I will update the article accordingly. What's the difference
between FullSeriesCollection and SeriesCollection (other than compatibility)?
△ ▽ • Reply • Share ›

Show more replies

Guz Man • 2 years ago


Can you comment on the difference between using ChartObjects vs Shapes?
Thanks.
△ ▽ • Reply • Share ›

Thomas Trautzsch • 2 years ago


Is it possible to draw shapes inside the charts plot area?
△ ▽ • Reply • Share ›

Steve • 3 years ago


I've got a number of charts in a spreadsheet (Excel 2013) and based on the size of the y axis values (4
figures to 6 figures, the y axis shifts to the left or right. I'd like to specify a location for the y & x axis that
are fixed so the 'chart area' doesn't move around. Sort of like an 'align right' where the margin remains
fixed.
△ ▽ • Reply • Share ›

Hidayat Farizi • 3 years ago


I normally work with multiple "scatter-type" charts and it is always tricky whenever I want to see where
the source data is coming from. Is there a vba that would allow excel to highlight the range of source data
from a selected chart series?

Thanks
△ ▽ • Reply • Share ›

Zach • 3 years ago


Hi spreadsheetguru,

I am having a big problem here, how do I create a chart with multiple series where each series is a
unique array?
△ ▽ • Reply • Share ›

Sam Dickey • 4 years ago


How does one control color of the plot area?. is it possible to control color of the plot area based on a cell
value?
△ ▽ • Reply • Share ›

ALSO ON THESPREADSHEETGURU

How To Build A Modern-Looking VBA Userform How To Create A Filtering Search Box For Your
13 comments • 3 months ago Excel Data
Daniel Lamarche — Good taste with userforms can 1 comment • a year ago
Avatarmake the difference between users liking them or J M — Love the tutorial! Any way to add option
not so much...Thanks for good example! Avatarbuttons to change the DataRange from the active
sheet to other sheets in the workbook?

How To Determine Hex Color Codes For VBA How To Automatically Run Excel VBA Macros
Userforms Daily
2 comments • 2 months ago 7 comments • 2 months ago
Jon Peltier — You can just paste the decimal color Andrija — click on " Run whether or not user is
Avatarvalue, calculated from RGB(red, green, blue) into Avatarlogged on or not"..."MS Office applications will only
the Properties pane. VBA will convert it to hex … run under an active foreground user session. …

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy

https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 7/8
7/6/2019 The VBA Coding Guide For Excel Charts & Graphs — The Spreadsheet Guru

A liate Program | About | Example Files

Guru Solutions, LLC | © 2015-2019 | ALL RIGHTS RESERVED


Excel, PowerPoint, Word, & the rest of the O ce Suite are registered trademarks of the Microsoft Corporation
This site is not a liated with Microsoft Corporation.

https://www.thespreadsheetguru.com/blog/2015/3/1/the-vba-coding-guide-for-excel-charts-graph 8/8

Das könnte Ihnen auch gefallen