Charts and graphs are one of the best features of Excel; they are very flexible and can be used to make some very advanced visualization. However, this flexibility means there are hundreds of different options. We can create exactly the visualization we want but it 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. This post is a guide to using VBA for Charts and Graphs in Excel.
The code examples below demonstrate some of the most common chart options with VBA. Hopefully you can put these to good use and automate your chart creation and modifications.
While it might be tempting to skip straight to the section you need, I recommend you read the first section in full. Understanding the Document Object Model (DOM) is essential to understand how VBA can be used with charts and graphs in Excel.
In Excel 2013, many changes were introduced to the charting engine and Document Object Model. 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.
Adapting the code to your requirements
It is not feasible to provide code for every scenario you might come across; there are just too many. But, by applying the principles and methods in this post, you will be able to do almost anything you want with charts in Excel using VBA.
Understanding the Document Object Model
The Document Object Model (DOM) is a term that describes how things are structured in Excel. For example:
- A Workbook contains Sheets
- A Sheet contains Ranges
- A Range contains an Interior
- An Interior contains a color setting
Therefore, to change a cell color to red, we would reference this as follows:
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.
ActiveWorkbook.Sheets("Sheet1").ChartObjects("Chart 1").Height = 300
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.
ActiveWorkbook.ChartObjects("Chart 1").Height = 300
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.
ActiveWorkbook.Sheets("Sheet1").ChartObjects("Chart 1").Height = 300
With this knowledge, we can refer to any element of any chart using Excel’s DOM.
Chart Objects vs. Charts vs. Chart Sheets
One of the things which makes the DOM for charts complicated is that many things exist in many places. For example, a chart can be an embedded chart on the face of a worksheet, or as a separate chart sheet.
- On the worksheet itself, we find ChartObjects. Within each ChartObject is a Chart. Effectively a ChartObject is a container that holds a Chart.
- A Chart is also a stand-alone sheet that does not have a ChartObject around it.
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.
Writing code to work on either chart type
We want to write code that will work on any chart; we do this by creating a variable that holds the reference to a Chart.
Create a variable to refer to a Chart inside a ChartObject:
Dim cht As Chart
Set cht = Sheets("Sheet1").ChartObjects("Chart 1").Chart
Create a variable to refer to a Chart which is a sheet:
Dim cht As Chart
Set cht = Sheets("Chart 1")
Now we can write VBA code for a Chart sheet or a chart inside a ChartObject by referring to the Chart using cht:
cht.ChartTitle.Text = "My Chart Title"
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.
Inserting charts
In this first section, we create charts. Please note that some of the individual lines of code are included below in their relevant sections.
Create a chart from a blank chart
Sub CreateChart()
'Declare variables
Dim rng As Range
Dim cht As Object
'Create a blank chart
Set cht = ActiveSheet.Shapes.AddChart2
'Declare the data range for the chart
Set rng = ActiveSheet.Range("A2:B9")
'Add the data to the chart
cht.Chart.SetSourceData Source:=rng
'Set the chart type
cht.Chart.ChartType = xlColumnClustered
End Sub
Reference charts on a worksheet
In this section, we look at the methods used to reference a chart contained on a worksheet.
Active Chart
Create a Chart variable to hold the ActiveChart:
Dim cht As Chart
Set cht = ActiveChart
Chart Object by name
Create a Chart variable to hold a specific chart by name.
Dim cht As Chart
Set cht = Sheets("Sheet1").ChartObjects("Chart 1").Chart
Chart object by number
If there are multiple charts on a worksheet, they can be referenced by their number:
- 1 = the first chart created
- 2 = the second chart created
- etc, etc.
Dim cht As Chart
Set cht = Sheets("Sheet1").ChartObjects(1).Chart
Loop through all Chart Objects
If there are multiple ChartObjects on a worksheet, we can loop through each:
Dim chtObj As ChartObject
For Each chtObj In Sheets("Sheet1").ChartObjects
'Include the code to be applied to each ChartObjects
'refer to the Chart using chtObj.cht.
Next chtObj
Loop through all selected Chart Objects
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.
Dim obj As Object
'Check if any charts have been selected
If Not ActiveChart Is Nothing Then
Call AnotherMacro(ActiveChart)
Else
For Each obj In Selection
'If more than one chart selected
If TypeName(obj) = "ChartObject" Then
Call AnotherMacro(obj.Chart)
End If
Next
End If
Reference chart sheets
Now let’s move on to look at the methods used to reference a separate chart sheet.
Active Chart
Set up a Chart variable to hold the ActiveChart:
Dim cht As Chart
Set cht = ActiveChart
Note: this is the same code as when referencing the active chart on the worksheet.
Chart sheet by name
Set up a Chart variable to hold a specific chart sheet
Dim cht As Chart
Set cht = Sheets("Chart 1")
Loop through all chart sheets in a workbook
The following code will loop through all the chart sheets in the active workbook.
Dim cht As Chart
For Each cht In ActiveWorkbook.Charts
Call AnotherMacro(cht)
Next cht
Basic chart settings
This section contains basic chart settings.
All codes start with cht., as they assume a chart has been referenced using the codes above.
Change chart type
'Change chart type - these are common examples, others do exist.
cht.ChartType = xlArea
cht.ChartType = xlLine
cht.ChartType = xlPie
cht.ChartType = xlColumnClustered
cht.ChartType = xlColumnStacked
cht.ChartType = xlColumnStacked100
cht.ChartType = xlArea
cht.ChartType = xlAreaStacked
cht.ChartType = xlBarClustered
cht.ChartType = xlBarStacked
cht.ChartType = xlBarStacked100
Create an empty ChartObject on a worksheet
'Create an empty chart embedded on a worksheet.
Set cht = Sheets("Sheet1").Shapes.AddChart2.Chart
Select the source for a chart
'Select source for a chart
Dim rng As Range
Set rng = Sheets("Sheet1").Range("A1:B4")
cht.SetSourceData Source:=rng
Delete a chart object or chart sheet
'Delete a ChartObject or Chart sheet
If TypeName(cht.Parent) = "ChartObject" Then
cht.Parent.Delete
ElseIf TypeName(cht.Parent) = "Workbook" Then
cht.Delete
End If
Change the size or position of a chart
'Set the size/position of a ChartObject - method 1
cht.Parent.Height = 200
cht.Parent.Width = 300
cht.Parent.Left = 20
cht.Parent.Top = 20
'Set the size/position of a ChartObject - method 2
chtObj.Height = 200
chtObj.Width = 300
chtObj.Left = 20
chtObj.Top = 20
Change the visible cells setting
'Change the setting to show only visible cells
cht.PlotVisibleOnly = False
Change the space between columns/bars (gap width)
'Change the gap space between bars
cht.ChartGroups(1).GapWidth = 50
Change the overlap of columns/bars
'Change the overlap setting of bars
cht.ChartGroups(1).Overlap = 75
Remove outside border from chart object
'Remove the outside border from a chart
cht.ChartArea.Format.Line.Visible = msoFalse
Change color of chart background
'Set the fill color of the chart area
cht.ChartArea.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
'Set chart with no background color
cht.ChartArea.Format.Fill.Visible = msoFalse
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.
Set min and max of chart axis
'Set chart axis min and max
cht.Axes(xlValue).MaximumScale = 25
cht.Axes(xlValue).MinimumScale = 10
cht.Axes(xlValue).MaximumScaleIsAuto = True
cht.Axes(xlValue).MinimumScaleIsAuto = True
Display or hide chart axis
'Display axis
cht.HasAxis(xlCategory) = True
'Hide axis
cht.HasAxis(xlValue, xlSecondary) = False
Display or hide chart title
'Display axis title
cht.Axes(xlCategory, xlSecondary).HasTitle = True
'Hide axis title
cht.Axes(xlValue).HasTitle = False
Change chart axis title text
'Change axis title text
cht.Axes(xlCategory).AxisTitle.Text = "My Axis Title"
Reverse the order of a category axis
'Reverse the order of a catetory axis
cht.Axes(xlCategory).ReversePlotOrder = True
'Set category axis to default order
cht.Axes(xlCategory).ReversePlotOrder = False
Gridlines
Gridlines help a user to see the relative position of an item compared to the axis.
Add or delete 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).MajorGridlines.Delete
cht.Axes(xlCategory).MinorGridlines.Delete
Change color of gridlines
'Change colour of gridlines
cht.Axes(xlValue).MajorGridlines.Format.Line.ForeColor.RGB = RGB(255, 0, 0)
Change transparency of gridlines
'Change transparency of gridlines
cht.Axes(xlValue).MajorGridlines.Format.Line.Transparency = 0.5
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.
Display or hide chart title
'Display chart title
cht.HasTitle = True
'Hide chart title
cht.HasTitle = False
Change chart title text
'Change chart title text
cht.ChartTitle.Text = "My Chart Title"
Position the chart title
'Position the chart title
cht.ChartTitle.Left = 10
cht.ChartTitle.Top = 10
Format the chart title
'Format the chart title
cht.ChartTitle.TextFrame2.TextRange.Font.Name = "Calibri"
cht.ChartTitle.TextFrame2.TextRange.Font.Size = 16
cht.ChartTitle.TextFrame2.TextRange.Font.Bold = msoTrue
cht.ChartTitle.TextFrame2.TextRange.Font.Bold = msoFalse
cht.ChartTitle.TextFrame2.TextRange.Font.Italic = msoTrue
cht.ChartTitle.TextFrame2.TextRange.Font.Italic = msoFalse
Chart Legend
The chart legend provides a color key to identify each series in the chart.
Display or hide the chart legend
'Display the legend
cht.HasLegend = True
'Hide the legend
cht.HasLegend = False
Position the legend
'Position the legend
cht.Legend.Position = xlLegendPositionTop
cht.Legend.Position = xlLegendPositionRight
cht.Legend.Position = xlLegendPositionLeft
cht.Legend.Position = xlLegendPositionCorner
cht.Legend.Position = xlLegendPositionBottom
'Allow legend to overlap the chart.
'False = allow overlap, True = due not overlap
cht.Legend.IncludeInLayout = False
cht.Legend.IncludeInLayout = True
'Move legend to a specific point
cht.Legend.Left = 20
cht.Legend.Top = 200
cht.Legend.Width = 100
cht.Legend.Height = 25
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.
Background color of Plot Area
'Set background color of the plot area
cht.PlotArea.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
'Set plot area to no background color
cht.PlotArea.Format.Fill.Visible = msoFalse
Set position of Plot Area
'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.
Add a new chart series
'Add a new chart series
Set srs = cht.SeriesCollection.NewSeries
srs.Values = "=Sheet1!$C$2:$C$6"
srs.Name = "=""New Series"""
'Set the values for the X axis when using XY Scatter
srs.XValues = "=Sheet1!$D$2:$D$6"
Reference a chart series
Set up a Series variable to hold a chart series:
- 1 = First chart series
- 2 = Second chart series
- etc, etc.
Dim srs As Series
Set srs = cht.SeriesCollection(1)
Referencing a chart series by name
Dim srs As Series
Set srs = cht.SeriesCollection("Series Name")
Delete a chart series
'Delete chart series
srs.Delete
Loop through each chart series
Dim srs As Series
For Each srs In cht.SeriesCollection
'Do something to each series
'See the codes below starting with "srs."
Next srs
Change series data
'Change series source data and name
srs.Values = "=Sheet1!$C$2:$C$6"
srs.Name = "=""Change Series Name"""
Changing fill or line colors
'Change fill colour
srs.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
'Change line colour
srs.Format.Line.ForeColor.RGB = RGB(255, 0, 0)
Changing visibility
'Change visibility of line
srs.Format.Line.Visible = msoTrue
Changing line weight
'Change line weight
srs.Format.Line.Weight = 10
Changing line style
'Change line style
srs.Format.Line.DashStyle = msoLineDash
srs.Format.Line.DashStyle = msoLineSolid
srs.Format.Line.DashStyle = msoLineSysDot
srs.Format.Line.DashStyle = msoLineSysDash
srs.Format.Line.DashStyle = msoLineDashDot
srs.Format.Line.DashStyle = msoLineLongDash
srs.Format.Line.DashStyle = msoLineLongDashDot
srs.Format.Line.DashStyle = msoLineLongDashDotDot
Formatting markers
'Changer marker type
srs.MarkerStyle = xlMarkerStyleAutomatic
srs.MarkerStyle = xlMarkerStyleCircle
srs.MarkerStyle = xlMarkerStyleDash
srs.MarkerStyle = xlMarkerStyleDiamond
srs.MarkerStyle = xlMarkerStyleDot
srs.MarkerStyle = xlMarkerStyleNone
'Change marker border color
srs.MarkerForegroundColor = RGB(255, 0, 0)
'Change marker fill color
srs.MarkerBackgroundColor = RGB(255, 0, 0)
'Change marker size
srs.MarkerSize = 8
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.
Display or hide data labels
'Display data labels on all points in the series
srs.HasDataLabels = True
'Hide data labels on all points in the series
srs.HasDataLabels = False
Change the position of data labels
'Position data labels
'The label position must be a valid option for the chart type.
srs.DataLabels.Position = xlLabelPositionAbove
srs.DataLabels.Position = xlLabelPositionBelow
srs.DataLabels.Position = xlLabelPositionLeft
srs.DataLabels.Position = xlLabelPositionRight
srs.DataLabels.Position = xlLabelPositionCenter
srs.DataLabels.Position = xlLabelPositionInsideEnd
srs.DataLabels.Position = xlLabelPositionInsideBase
srs.DataLabels.Position = xlLabelPositionOutsideEnd
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.
Turn error bars on/off
'Turn error bars on/off
srs.HasErrorBars = True
srs.HasErrorBars = False
Error bar end cap style
'Change end style of error bar
srs.ErrorBars.EndStyle = xlNoCap
srs.ErrorBars.EndStyle = xlCap
Error bar color
'Change color of error bars
srs.ErrorBars.Format.Line.ForeColor.RGB = RGB(255, 0, 0)
Error bar thickness
'Change thickness of error bars
srs.ErrorBars.Format.Line.Weight = 5
Error bar direction settings
'Error bar settings
srs.ErrorBar Direction:=xlY, _
Include:=xlPlusValues, _
Type:=xlFixedValue, _
Amount:=100
'Alternatives options for the error bar settings are
'Direction:=xlX
'Include:=xlMinusValues
'Include:=xlPlusValues
'Include:=xlBoth
'Type:=xlFixedValue
'Type:=xlPercent
'Type:=xlStDev
'Type:=xlStError
'Type:=xlCustom
'Applying custom values to error bars
srs.ErrorBar Direction:=xlY, _
Include:=xlPlusValues, _
Type:=xlCustom, _
Amount:="=Sheet1!$A$2:$A$7", _
MinusValues:="=Sheet1!$A$2:$A$7"
Data points
Each data point on a chart series is known as a Point.
Reference a specific point
The following code will reference the first Point.
1 = First chart series
2 = Second chart series
etc, etc.
Dim srs As Series
Dim pnt As Point
Set srs = cht.SeriesCollection(1)
Set pnt = srs.Points(1)
Loop through all points
Dim srs As Series
Dim pnt As Point
Set srs = cht.SeriesCollection(1)
For Each pnt In srs.Points
'Do something to each point, using "pnt."
Next pnt
Point example VBA codes
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.
Turn on data label for a point
'Turn on data label
pnt.HasDataLabel = True
Set the data label position for a point
'Set the position of a data label
pnt.DataLabel.Position = xlLabelPositionCenter
Other useful chart macros
In this section, I’ve included other useful chart macros which are not covered by the example codes above.
Make chart cover cell range
The following code changes the location and size of the active chart to fit directly over the range G4:N20
Sub FitChartToRange()
'Declare variables
Dim cht As Chart
Dim rng As Range
'Assign objects to variables
Set cht = ActiveChart
Set rng = ActiveSheet.Range("G4:N20")
'Move and resize chart
cht.Parent.Left = rng.Left
cht.Parent.Top = rng.Top
cht.Parent.Width = rng.Width
cht.Parent.Height = rng.Height
End Sub
Export the chart as an image
The following code saves the active chart to an image in the predefined location
Sub ExportSingleChartAsImage()
'Create a variable to hold the path and name of image
Dim imagePath As String
Dim cht As Chart
imagePath = "C:UsersmarksDocumentsmyImage.png"
Set cht = ActiveChart
'Export the chart
cht.Export (imagePath)
End Sub
Resize all charts to the same size as the active chart
The following code resizes all charts on the Active Sheet to be the same size as the active chart.
Sub ResizeAllCharts()
'Create variables to hold chart dimensions
Dim chtHeight As Long
Dim chtWidth As Long
'Create variable to loop through chart objects
Dim chtObj As ChartObject
'Get the size of the first selected chart
chtHeight = ActiveChart.Parent.Height
chtWidth = ActiveChart.Parent.Width
For Each chtObj In ActiveSheet.ChartObjects
chtObj.Height = chtHeight
chtObj.Width = chtWidth
Next chtObj
End Sub
Bringing it all together
Just to prove how we can use these code snippets, I have created a macro to build bullet charts.
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.
The data looks like this:
The chart looks like this:
The code which achieves this is as follows:
Sub CreateBulletChart()
Dim cht As Chart
Dim srs As Series
Dim rng As Range
'Create an empty chart
Set cht = Sheets("Sheet3").Shapes.AddChart2.Chart
'Change chart title text
cht.ChartTitle.Text = "Bullet Chart with VBA"
'Hide the legend
cht.HasLegend = False
'Change chart type
cht.ChartType = xlBarClustered
'Select source for a chart
Set rng = Sheets("Sheet3").Range("A1:D4")
cht.SetSourceData Source:=rng
'Reverse the order of a catetory axis
cht.Axes(xlCategory).ReversePlotOrder = True
'Change the overlap setting of bars
cht.ChartGroups(1).Overlap = 100
'Change the gap space between bars
cht.ChartGroups(1).GapWidth = 50
'Change fill colour
Set srs = cht.SeriesCollection(1)
srs.Format.Fill.ForeColor.RGB = RGB(200, 200, 200)
Set srs = cht.SeriesCollection(2)
srs.Format.Fill.ForeColor.RGB = RGB(150, 150, 150)
Set srs = cht.SeriesCollection(3)
srs.Format.Fill.ForeColor.RGB = RGB(100, 100, 100)
'Add a new chart series
Set srs = cht.SeriesCollection.NewSeries
srs.Values = "=Sheet3!$B$7:$D$7"
srs.XValues = "=Sheet3!$B$5:$D$5"
srs.Name = "=""Actual"""
'Change chart type
srs.ChartType = xlXYScatter
'Turn error bars on/off
srs.HasErrorBars = True
'Change end style of error bar
srs.ErrorBars.EndStyle = xlNoCap
'Set the error bars
srs.ErrorBar Direction:=xlY, _
Include:=xlNone, _
Type:=xlErrorBarTypeCustom
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)
'Change thickness of error bars
srs.ErrorBars.Format.Line.Weight = 14
'Change marker type
srs.MarkerStyle = xlMarkerStyleNone
'Add a new chart series
Set srs = cht.SeriesCollection.NewSeries
srs.Values = "=Sheet3!$B$7:$D$7"
srs.XValues = "=Sheet3!$B$6:$D$6"
srs.Name = "=""Target"""
'Change chart type
srs.ChartType = xlXYScatter
'Turn error bars on/off
srs.HasErrorBars = True
'Change end style of error bar
srs.ErrorBars.EndStyle = xlNoCap
srs.ErrorBar Direction:=xlX, _
Include:=xlNone, _
Type:=xlErrorBarTypeCustom
srs.ErrorBar Direction:=xlY, _
Include:=xlBoth, _
Type:=xlFixedValue, _
Amount:=0.45
'Change color of error bars
srs.ErrorBars.Format.Line.ForeColor.RGB = RGB(255, 0, 0)
'Change thickness of error bars
srs.ErrorBars.Format.Line.Weight = 2
'Changer marker type
srs.MarkerStyle = xlMarkerStyleNone
'Set chart axis min and max
cht.Axes(xlValue, xlSecondary).MaximumScale = cht.SeriesCollection(1).Points.Count
cht.Axes(xlValue, xlSecondary).MinimumScale = 0
'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:
- VBA for Tables & List Objects
- VBA for PivotTables
- VBA to insert, move, delete and control pictures
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
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).
Do you need help adapting this post to your needs?
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.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- 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.
- 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:
Excel Chart VBA Examples and Tutorials
Excel charts are one of the awesome tools available to represent the data in rich visualized graphs. Here are the most frequently used Excel Chart VBA Examples and Tutorials. You can access chart objects, properties and dealing with the methods.
Here are the top most Excel Chart VBA Examples and Tutorials, show you how to deal with chart axis, chart titles, background colors,chart data source, chart types, series and many other chart objects.
Excel Chart VBA Examples and Tutorials – Learning Path
- Example tutorials on Creating Charts using Excel VBA:
- Example tutorials on Chart Type using Excel VBA:
- Example Tutorials on Formatting Chart Objects using Excel VBA:
- Example Tutorials on Chart Collection in Excel VBA:
- Other useful Examples and tutorials on Excel VBA Charting:
- Excel VBA Charting Constants and Enumerations:
- Example File for Free Download:
Creating Charts using Excel VBA
We can create the chart using different methods in Excel VBA, following are the various Excel Chart VBA Examples and Tutorials to show you creating charts in Excel using VBA.
1. Adding New Chart for Selected Data using Sapes.AddChart Method in Excel VBA
The following Excel Chart VBA Examples works similarly when we select some data and click on charts from Insert Menu and to create a new chart. This will create basic chart in an existing worksheet.
Sub ExAddingNewChartforSelectedData_Sapes_AddChart_Method() Range("C5:D7").Select ActiveSheet.Shapes.AddChart.Select End Sub
2. Adding New Chart for Selected Data using Charts.Add Method : Creating Chart Sheet in Excel VBA
The following Excel Chart VBA Examples method will add new chart into new worksheet by default. You can specify a location to embedded in a particular worksheet.
'Here is the other method to add charts using Chart Object. It will add a new chart for the selected data as new chart sheet. Sub ExAddingNewChartforSelectedData_Charts_Add_Method_SheetChart() Range("C5:D7").Select Charts.Add End Sub
3. Adding New Chart for Selected Data using Charts.Add Method : In Existing Sheet using Excel VBA
We can use the Charts.Add method to create a chart in existing worksheet. We can specify the position and location as shown below. This will create a new chart in a specific worksheet.
Sub ExAddingNewChartforSelectedData_Charts_Add_Method_InSheet() Range("C5:D7").Select Charts.Add ActiveChart.Location Where:=xlLocationAsObject, Name:="Sheet1" End Sub
4. Difference between embedded Chart and Chart Sheet in Excel:
Both are similar except event handlers, Chart Sheets will have the event handlers,we can write event programming for Chart Sheets. And the other type embedded charts can not support the event handlers. We can write classes to handle the events for the embedded chart, but not recommended.
We have seen multiple methods to create charts, but we cant set the chart at particular position using the above codes. You can use the ChartObjects.Add method to specify the position of the chart.
5. Adding New Chart for Selected Data using ChartObjects.Add Method in Excel VBA
ChartObjects.Add method is the best method as it is very easy to play with the chart objects to change the settings.
Sub ExAddingNewChartforSelectedData_ChartObjects_Add_Method() With ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") End With End Sub
6. Assigning Charts to an Object in Excel VBA
Here is another Excel Chart VBA Examples with ChartObjects, here we will assign to an Object and play with that.
Sub ExAddingNewChartforSelectedData_ChartObjects_Object() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") End Sub
7. Changing the Chart Position in Excel VBA
The following VBA example will show you how to change the chart position.
Sub ExAddingNewChartforSelectedData_Object_Position() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) cht.Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") cht.Left = 350 cht.Width = 400 cht.Top = 30 cht.Height = 200 End Sub
8. Align Chart Object at a Particular Range or Cell in Excel VBA
You can set the top,left, height and width properties of a chart object to align in a particular position.
Sub AlignChartAtParticularRange() ' Chart Align With ActiveSheet.ChartObjects(1) .Left = Range("A6").Left .Top = Range("A7").Top .Width = Range("D6").Left .Height = Range("D16").Top - Range("D6").Top End With End Sub
9. Use with statement while dealing with Charts and avoid the accessing the same object repeatedly in Excel VBA
If you are dealing with the same object, it is better to use with statement. It will make the program more clear to understand and executes faster.
Sub ExChartPostion_Object_Position() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Left = 350 .Width = 400 .Top = 30 .Height = 200 End With End Sub
10. You can use ActiveChart Object to access the active chart in Excel VBA
Active chart is the chart which is currently selected or activated in your active sheet.
Sub ExChartPostion_ActiveChart() ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300).Activate With ActiveChart .SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Parent.Left = 350 .Parent.Width = 400 .Parent.Top = 30 .Parent.Height = 200 End With End Sub
Top
Setting Chart Types using Excel VBA
We have verity of chart in Excel, we can use VBA to change and set the suitable chart type based on the data which we want to present. Below are the Excel Chart VBA Examples and Tutorials to change the chart type.
We can use Chart.Type property to set the chart type, here we can pass Excel chart constants or chart enumerations to set the chart type. Please refer the following table to understand the excel constants and enumerations.
11. Example to Change Chart type using Excel Chart Enumerations in Excel VBA
This Excel Chart VBA Example will use 1 as excel enumeration to plot the Aria Chart. Please check here list of enumerations available for Excel VBA Charting
Sub Ex_ChartType_Enumeration() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = 1 ' for aria chart End With End Sub
12. Example to Change Chart type using Excel Chart Constants in VBA
This Excel Chart VBA Example will use xlArea as excel constant to plot the Aria Chart. Please check here for list of enumerations available in Excel VBA Charting
Sub Ex_ChartType_xlConstant() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlArea End With End Sub
xlConstants is recommended than Excel Enumeration, as it is easy to understand and remember. Following are frequently used chart type examples:
13. Example to set the type as a Pie Chart in Excel VBA
The following VBA code using xlPie constant to plot the Pie chart. Please check here for list of enumerations available in Excel VBA Charting
Sub Ex_ChartType_Pie_Chart() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlPie End With End Sub
14. Example to set the chart type as a Line Chart in Excel VBA
The following VBA code using xlLine constant to plot the Pie chart. Please check here for list of enumerations available in Excel VBA Charting
Sub Ex_ChartType_Line_Chart() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlLine End With End Sub
15. Example to set the chart type as a Bar Chart in Excel VBA
The following VBA code using xlBar constant to plot the Pie chart. Please check here for list of enumerations available in Excel VBA Charting
Sub Ex_ChartType_Bar_Chart() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlBar End With End Sub
16. Example to set the chart type as a XYScatter Chart in Excel VBA
The following code using xlXYScatter constant to plot the Pie chart. Please check here for list of enumerations available in Excel VBA Charting
Sub Ex_ChartType_XYScatter_Chart() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlXYScatter End With End Sub
Here is the complete list of Excel Chart Types, Chart Enumerations and Chart Constants:
Top
Formatting Chart Objects using Excel VBA
Below are Excel Chart VBA Examples to show you how to change background colors of charts, series and changing the different properties of charts like Chart Legends, Line Styles, Number Formatting. You can also find the examples on Chart Axis and Chart Axes Setting and Number Formats.
17. Changing Chart Background Color – Chart Aria Interior Color in Excel VBA
The following VBA code will change the background color of the Excel Chart.
Sub Ex_ChartAriaInteriorColor() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.ChartArea.Interior.ColorIndex = 3 End With End Sub
18. Changing PlotAria Background Color – PlotAria Interior Color in Excel VBA
The following code will change the background color of Plot Area in Excel VBA.
Sub Ex_PlotAriaInteriorColor() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.PlotArea.Interior.ColorIndex = 5 End With End Sub
19.Changing Chart Series Background Color – Series Interior Color in Excel VBA
The following code is for changing the background color of a series using Excel VBA.
Sub Ex_SeriesInteriorColor() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.SeriesCollection(1).Format.Fill.ForeColor.RGB = rgbRed .Chart.SeriesCollection(2).Interior.ColorIndex = 5 End With End Sub
20. Changing Chart Series Marker Style in Excel VBA
Here is the code to change the series marker style using Excel VBA, you can change to circle, diamond, square,etc. Check the excel constants and enumerations for more options available in excel vba.
Sub Ex_ChangingMarkerStyle() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlLine .Chart.SeriesCollection(1).MarkerStyle = 7 End With End Sub
21. Changing Chart Series Line Style in Excel VBA
Here is the code to change the line color using Excel VBA, it will change the line style from solid to dash. Check the excel constants for more options.
Sub Ex_ChangingLineStyle() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlLine .Chart.SeriesCollection(1).Border.LineStyle = xlDash End With End Sub
22. Changing Chart Series Border Color in Excel VBA
Here is the code for changing series borders in Excel VBA.
Sub Ex_ChangingBorderColor() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlBar .Chart.SeriesCollection(1).Border.ColorIndex = 3 End With End Sub
23. Change Chart Axis NumberFormat in Excel VBA
This code will change the chart axis number format using excel vba.
Sub Ex_ChangeAxisNumberFormat() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlLine .Chart.Axes(xlValue).TickLabels.NumberFormat = "0.00" End With End Sub
24. Formatting Axis Labels: Changing Axis Font to Bold using Excel VBA
The following example is for formating Axis labels using Excel VBA.
Sub Ex_ChangeAxisFormatFontBold() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlLine .Chart.Axes(xlCategory).TickLabels.Font.FontStyle = "Bold" End With End Sub
25. Two Y-axes Left and Right of Charts(Primary Axis and Secondary Axis) using Excel VBA
This code will set the series 2 into secondary Axis using Excel VBA.
Sub Ex_ChangeAxistoSecondary() Dim cht As Object Set cht = ActiveSheet.ChartObjects.Add(Left:=300, Width:=300, Top:=10, Height:=300) With cht .Chart.SetSourceData Source:=Sheets("Temp").Range("C5:D7") .Chart.Type = xlLine .Chart.SeriesCollection(2).AxisGroup = 2 End With End Sub
Top
Chart Collection in Excel VBA
You can use ChartObject Collection to loop through the all charts in worksheet or workbook using Excel VBA. And do whatever you want to do with that particular chart. Here are Excel Chart VBA Examples to deal with Charts using VBA.
26. Set equal widths and heights for all charts available in a Worksheet using Excel VBA
Following is the Excel VBA code to change the chart width and height.
Sub Ex_ChartCollections_Change_widths_heights() Dim cht As Object For Each cht In ActiveSheet.ChartObjects cht.Width = 400 cht.Height = 200 Next End Sub
27. Delete All Charts in a Worksheet using Excel VBA
Following is the Excel VBA example to delete all charts in worksheet.
Sub Ex_DeleteAllCharts() Dim cht As Object For Each cht In ActiveSheet.ChartObjects cht.Delete Next End Sub
Top
Other useful Examples and tutorials on Excel VBA Charting
28. Set Chart Data Source using Excel VBA
Below is the Excel Chart VBA Example to set the chart data source. You can set it by using .SetSourceData Source property of a chart
Sub Ex_ChartDataSource() Dim cht As Chart 'Add new chart ActiveSheet.Shapes.AddChart.Select With ActiveChart 'Specify source data and orientation .SetSourceData Source:=Sheet1.Range("A1:C5") End With End Sub
29. Swap or Switch Rows and Columns in Excel Charts using VBA
Here is the excel VBA code to swap the Rows to Columns.
Sub Ex_SwitchRowsColumns() Dim cht As Chart 'Add new chart ActiveSheet.Shapes.AddChart.Select With ActiveChart 'Specify source data and orientation .SetSourceData Source:=Sheets("Temp").Range("C5:D7"), PlotBy:=xlRows ' you can use xlColumns to swith it End With End Sub
30. Set Chart Data Labels and Legends using Excel VBA
You can set Chart Data Labels and Legends by using SetElement property in Excl VBA
Sub Ex_AddDataLabels() Dim cht As Chart 'Add new chart ActiveSheet.Shapes.AddChart.Select With ActiveChart 'Specify source data and orientation .SetSourceData Source:=Sheet1.Range("A1:B5"), PlotBy:=xlColumns 'Set Chart type .ChartType = xlPie 'set data label at center .SetElement (msoElementDataLabelCenter) 'set legend at bottom .SetElement (msoElementLegendBottom) End With End Sub
31. Changing Axis Titles of a Chart in Excel VBA
Following is the code to change the chart Axis titles using Excel VBA..
Sub Ex_ChangeAxisTitles() activechart.chartobjects(1).activate ActiveChart.Axes(xlCategory).HasTitle = True ActiveChart.Axes(xlCategory).AxisTitle.Text = "Quarter" ActiveChart.Axes(xlValue).HasTitle = True ActiveChart.Axes(xlValue).AxisTitle.Text = "Sales" End Sub
32. Change Titles of a Chart using Excel VBA
Following is the code to change the chart titles using Excel VBA..
Sub Ex_ChangeChartTitles() ActiveSheet.ChartObjects(1).Activate ActiveChart.HasTitle = True ActiveChart.ChartTitle.Text = "Overal Summary" End Sub
33. Send an Excel Chart to an Outlook email using VBA
Download Example File:
ANALYSIS TABS – SendExcelChartToOutLook.xlsm
Following is the code to Send an Excel Chart to an Outlook email using VBA.
Sub SendChartThroughMail() 'Add refernce to Microsoft Outlook object Library Dim olMail As MailItem Dim objOL As Object Dim sImgPath As String Dim sHi As String Dim sBody As String Dim sThanks As String ' Saving chart as image sImgPath = ThisWorkbook.Path & "Temp_" & Format(Now(), "DD_MM_YY_HH_MM_SS") & ".bmp" Sheets("Sheet1").ChartObjects(1).Chart.Export sImgPath 'creating html body with image sHi = "<font size='3' color='black'>" & "Hi," & "<br> <br>" & "Here is the required solution: " & "<br> <br> </font>" sBody = "<p align='Left'><img src=""cid:" & Mid(sImgPath, InStrRev(sImgPath, "") + 1) & """ width=400 height=300 > <br> <br>" sThanks = "<font size='3'>" & "Many thanks - ANALYSISTABS.COM <br>The Complete Reference For Analyst <br> website:<A HREF=""https://www.analysistabs.com""> analysistabs.com</A>" & "<br> <br> </font>" 'sending the email Set objOL = CreateObject("Outlook.Application") Set olMail = objOL.CreateItem(olMailItem) With olMail .To = "youremail@orgdomain.com" .Subject = "ANALYSISTABS.COM: Test Mail with chart" .Attachments.Add sImgPath .HTMLBody = sHi & sBody & sThanks .Display End With 'Delete the saved chart Kill sImgPath 'Free-up the objects Set olMail = Nothing Set olApp = Nothing End Sub
Top
Excel VBA Chart Constants and Enumerations
Chart Types, Constants and Enumerations
CHART TYPE | VBA CONSTANT | VALUE |
AREA Charts |
||
AREA | xlArea | 1 |
STACKED AREA | xlAreaStacked | 76 |
100% STACKED AREA | xlAreaStacked100 | 77 |
3D AREA | xl3DArea | -4098 |
3D STACKED AREA | xl3DAreaStacked | 78 |
3D 100% STACKED AREA | xl3DAreaStacked100 | 79 |
BAR Charts |
||
3D CLUSTERED BAR | xl3DBarClustered | 60 |
3D STACKED BAR | xl3DBarStacked | 61 |
3D 100% STACKED BAR | xl3DBarStacked100 | 62 |
CLUSTERED BAR | xlBarClustered | 57 |
STACKED BAR | xlBarStacked | 58 |
100% STACKED BAR | xlBarStacked100 | 59 |
CLUSTERED CONE BAR | xlConeBarClustered | 102 |
STACKED CONE BAR | xlConeBarStacked | 103 |
100% STACKED CONE BAR | xlConeBarStacked100 | 104 |
CLUSTERED CYLINDER BAR | xlCylinderBarClustered | 95 |
STACKED CYLINDER BAR | xlCylinderBarStacked | 96 |
100% STACKED CYLINDER BAR | xlCylinderBarStacked100 | 97 |
CLUSTERED PYRAMID BAR | xlPyramidBarClustered | 109 |
STACKED PYRAMID BAR | xlPyramidBarStacked | 110 |
100% STACKED PYRAMID BAR | xlPyramidBarStacked100 | 111 |
BUBBLE Charts | ||
3D BUBBLE, BUBBLE WITH 3D EFFECTS | xlBubble3DEffect | 87 |
BUBBLE | xlBubble | 15 |
COLUMN Charts |
||
3D CLUSTERED COLUMN | xl3DColumnClustered | 54 |
3D COLUMN | xl3DColumn | -4100 |
3D CONE COLUMN | xlConeCol | 105 |
3D CYLINDER COLUMN | xlCylinderCol | 98 |
3D PYRAMID COLUMN | xlPyramidCol | 112 |
3D STACKED COLUMN | xl3DColumnStacked | 55 |
3D 100% STACKED COLUMN | xl3DColumnStacked100 | 56 |
CLUSTERED COLUMN | xlColumnClustered | 51 |
STACKED COLUMN | xlColumnStacked | 52 |
100% STACKED COLUMN | xlColumnStacked100 | 53 |
CLUSTERED CONE COLUMN | xlConeColClustered | 99 |
STACKED CONE COLUMN | xlConeColStacked | 100 |
100% STACKED CONE COLUMN | xlConeColStacked100 | 101 |
CLUSTERED CYLINDER COLUMN | xlCylinderColClustered | 92 |
STACKED CYLINDER COLUMN | xlCylinderColStacked | 93 |
100% STACKED CYLINDER COLUMN | xlCylinderColStacked100 | 94 |
CLUSTERED PYRAMID COLUMN | xlPyramidColClustered | 106 |
STACKED PYRAMID COLUMN | xlPyramidColStacked | 107 |
100% STACKED PYRAMID COLUMN | xlPyramidColStacked100 | 108 |
DOUGHNUT Charts |
||
DOUGHNUT | xlDoughnut | -4120 |
EXPLODED DOUGHNUT | xlDoughnutExploded | 80 |
LINE Charts |
||
3D LINE | xl3DLine | -4101 |
LINE | xlLine | 4 |
LINE WITH MARKERS | xlLineMarkers | 65 |
STACKED LINE | xlLineStacked | 63 |
100% STACKED LINE | xlLineStacked100 | 64 |
STACKED LINE WITH MARKERS | xlLineMarkersStacked | 66 |
100% STACKED LINE WITH MARKERS | xlLineMarkersStacked100 | 67 |
PIE Charts |
||
3D PIE | xl3DPie | -4102 |
3D EXPLODED PIE | xl3DPieExploded | 70 |
BAR OF PIE | xlBarOfPie | 71 |
EXPLODED PIE | xlPieExploded | 69 |
PIE | xlPie | 5 |
PIE OF PIE | xlPieOfPie | 68 |
RADAR Charts |
||
RADAR | xlRadar | -4151 |
FILLED RADAR | xlRadarFilled | 82 |
RADAR WITH DATA MARKERS | xlRadarMarkers | 81 |
SCATTER Charts |
||
SCATTER | xlXYScatter | -4169 |
SCATTER WITH LINES | xlXYScatterLines | 74 |
SCATTER WITH LINES AND NO DATA MARKERS | xlXYScatterLinesNoMarkers | 75 |
SCATTER WITH SMOOTH LINES | xlXYScatterSmooth | 72 |
SCATTER WITH SMOOTH LINES AND NO DATA MARKERS | xlXYScatterSmoothNoMarkers | 73 |
STOCK Charts |
||
STOCK HLC (HIGH-LOW-CLOSE) | xlStockHLC | 88 |
STOCK OHLC (OPEN-HIGH-LOW-CLOSE) | xlStockOHLC | 89 |
STOCK VHLC (VOLUME-HIGH-LOW-CLOSE) | xlStockVHLC | 90 |
STOCK VOHLC (VOLUME-OPEN-HIGH-LOW-CLOSE) | xlStockVOHLC | 91 |
SURFACE Charts |
||
3D SURFACE | xlSurface | 83 |
3D SURFACE WIREFRAME | xlSurfaceWireframe | 84 |
SURFACE TOP VIEW | xlSurfaceTopView | 85 |
SURFACE TOP VIEW WIREFRAME | xlSurfaceTopViewWireframe | 86 |
Marker Styles, Constants and Enumerations
Marker Styles | Name | Value |
Automatic markers | xlMarkerStyleAutomatic | -4105 |
Circular markers | xlMarkerStyleCircle | 8 |
Long bar markers | xlMarkerStyleDash | -4115 |
Diamond-shaped markers | xlMarkerStyleDiamond | 2 |
Short bar markers | xlMarkerStyleDot | -4118 |
No markers | xlMarkerStyleNone | -4142 |
Picture markers | xlMarkerStylePicture | -4147 |
Square markers with a plus sign | xlMarkerStylePlus | 9 |
Square markers | xlMarkerStyleSquare | 1 |
Square markers with an asterisk | xlMarkerStyleStar | 5 |
Triangular markers | xlMarkerStyleTriangle | 3 |
Square markers with an X | xlMarkerStyleX | -4168 |
Line Styles, Constants and Enumerations
Line Style | Value |
xlContinuous | 1 |
xlDash | -4115 |
xlDashDot | 4 |
xlDashDotDot | 5 |
xlDot | -4118 |
xlDouble | -4119 |
xlLineStyleNone | -4142 |
xlSlantDashDot | 13 |
Example file to Download
You can download the example file and have a look into the working codes.
ANALYSISTABS- Chart VBA Examples
Reference:
MSDN
A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.
Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates
Excel Pack
50+ Excel PM Templates
PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates
Related Posts
-
- Excel Chart VBA Examples and Tutorials – Learning Path
- Creating Charts using Excel VBA
- 1. Adding New Chart for Selected Data using Sapes.AddChart Method in Excel VBA
- 2. Adding New Chart for Selected Data using Charts.Add Method : Creating Chart Sheet in Excel VBA
- 3. Adding New Chart for Selected Data using Charts.Add Method : In Existing Sheet using Excel VBA
- 4. Difference between embedded Chart and Chart Sheet in Excel:
- 5. Adding New Chart for Selected Data using ChartObjects.Add Method in Excel VBA
- 6. Assigning Charts to an Object in Excel VBA
- 7. Changing the Chart Position in Excel VBA
- 8. Align Chart Object at a Particular Range or Cell in Excel VBA
- 9. Use with statement while dealing with Charts and avoid the accessing the same object repeatedly in Excel VBA
- 10. You can use ActiveChart Object to access the active chart in Excel VBA
- Setting Chart Types using Excel VBA
- 11. Example to Change Chart type using Excel Chart Enumerations in Excel VBA
- 12. Example to Change Chart type using Excel Chart Constants in VBA
- 13. Example to set the type as a Pie Chart in Excel VBA
- 14. Example to set the chart type as a Line Chart in Excel VBA
- 15. Example to set the chart type as a Bar Chart in Excel VBA
- 16. Example to set the chart type as a XYScatter Chart in Excel VBA
- Formatting Chart Objects using Excel VBA
- 17. Changing Chart Background Color – Chart Aria Interior Color in Excel VBA
- 18. Changing PlotAria Background Color – PlotAria Interior Color in Excel VBA
- 19.Changing Chart Series Background Color – Series Interior Color in Excel VBA
- 20. Changing Chart Series Marker Style in Excel VBA
- 21. Changing Chart Series Line Style in Excel VBA
- 22. Changing Chart Series Border Color in Excel VBA
- 23. Change Chart Axis NumberFormat in Excel VBA
- 24. Formatting Axis Labels: Changing Axis Font to Bold using Excel VBA
- 25. Two Y-axes Left and Right of Charts(Primary Axis and Secondary Axis) using Excel VBA
- Chart Collection in Excel VBA
- 26. Set equal widths and heights for all charts available in a Worksheet using Excel VBA
- 27. Delete All Charts in a Worksheet using Excel VBA
- Other useful Examples and tutorials on Excel VBA Charting
- 28. Set Chart Data Source using Excel VBA
- 29. Swap or Switch Rows and Columns in Excel Charts using VBA
- 30. Set Chart Data Labels and Legends using Excel VBA
- 31. Changing Axis Titles of a Chart in Excel VBA
- 32. Change Titles of a Chart using Excel VBA
- 33. Send an Excel Chart to an Outlook email using VBA
- Excel VBA Chart Constants and Enumerations
- Chart Types, Constants and Enumerations
- Marker Styles, Constants and Enumerations
- Line Styles, Constants and Enumerations
- Example file to Download
VBA Reference
Effortlessly
Manage Your Projects
120+ Project Management Templates
Seamlessly manage your projects with our powerful & multi-purpose templates for project management.
120+ PM Templates Includes:
30 Comments
-
Tim
December 18, 2013 at 11:33 PM — ReplyHI there PNRao,
This is a really great reference – in the past, I’ve beat around the object browser as well. I use MS Graph in an MS Access application (currently A2007 in process of being upgraded from A2003). I have numerous controls to do some of the tasks you’ve identified here and others as well. I also have a button for the very few advanced users UI have to be able to actually open MS Graph in a separate window and do formatting there. What I’m trying to figure out how to do is enumerate through ALL properties of a chart and save them as an array or tab delimited string in a database (Oracle in this case) field.
Is there anyway to do this? I’ve done lots of the sorts of enumeration that you show show excellently here. What I would very much like to do is to be able to enumerate all formatting properties of a chart to be able to store it (above) and retrieve.
Do you have any ideas? Thanks in advance,
—
Tim -
PNRao
December 19, 2013 at 11:30 AM — ReplyHi Tim,
It is good idea to store all properties as enumerations in a field and draw the charts based on the requirement. You can consider the following things to save in the data base.
1. Chart Type
2. Data Source
3. Axes (Primary/Secondary)
4. Border
5. Number Format
6. Legend Alignment
7. Data Labels
8. Chart titleYou can make all the above properties as dynamic and the other things like Colors and minimum and maximum axis should be automatic.
And you can provide UI to format the charts using drop-down lists and Text boxes. For example, you can show different chart types in drop-down and chart type can be changed based on the user selection. You can provide text box to enter the chart title, it should save in your database for chart titles enumeration to reflect on your chart.
Hope this helps, let me know if you need any help on this.
Thanks
PNRao! -
kamran
February 28, 2014 at 3:44 PM — ReplyOne of the best Tutorial for VBA macro.
-
Antoni
April 23, 2014 at 9:02 PM — ReplyHi,
My boss has asked me to do many graphics chars, i love the example and explanations that have left at this web, I would like to do what our friend says PNRao, please have you any example of how to do it?
Thank you very much.
Antoni. -
PNRao
April 24, 2014 at 8:48 PM — ReplyHi Antoni,
We can automate charting using VBA. We have provided some examples in download page. You can download and see the examples, let us know if you need any help.
Thanks-PNRao!
-
Antoni
April 25, 2014 at 8:15 PM — ReplyHi PNRao,
I can’t found examples in the Download section, can you help me please?, or can you send me a links?
Thank you.
-
PNRao
April 26, 2014 at 12:08 AM — ReplyHi Antoni,
I have added the example file at end of the post. Please download and see the code.Thanks-PNRao!
-
Sam
May 4, 2014 at 9:32 AM — ReplyHi,
I am having a task, in which i need to copy chart from one excel sheet to another excel sheet.
So can you please help me in this.
Thanks,
Sam -
PNRao
May 4, 2014 at 11:40 AM — ReplyHi Sam,
You can use the Copy method as shown below:
[vb]
Sub sbVBA_Chart_Copy()
Sheet1.ChartObjects(«Chart 1»).Copy ‘Sheet name and Chart Object name to be copied
Sheet2.Activate ‘Activate your destination Sheet
Range(«G1»).Select ‘Select your destination cell
ActiveSheet.Paste ‘Now Paste
End Sub
[/vb]Thanks-PNRao!
-
Ross
December 29, 2014 at 9:02 PM — ReplyHi PNRao,
Thanks for the above it’s really helpful, although I’m still stuck!
Is there a way to so that when making a graph it has a certain destination within the sheet so it’s not pasted over my data?
Thank you!!
-
เสื้อคู่
May 25, 2015 at 3:43 PM — ReplyHi, this weekend is pleasant in favor of me, since this moment i am reading
this great informative post here at my residence. -
Nkhoma Kenneth
October 4, 2015 at 1:27 PM — ReplyThanks very much for the tutorial, it is a great one indeed and very helpful.
Thanks to you, i have learn’t something.
-
Richard
December 1, 2015 at 4:59 PM — ReplyHi Guys
Great info – ThanksI’m trying to automate some graph formatting, and whilst I’ve worked out how to change the range for a xlTimeScale based graph, I want an easy way for the user to define which graphs need to be scaled to current month rather than all year.
I thought of putting a text string into the Alt Text Description box (found under / but how do I read that field from a macro?
If it were a shape I could use something like shapeDesc = sheet(1).Shapes(1).AlternativeText but that doesn’t work for ChartObjects.
Any ideas?
Thanks
RichardAlways learning …
-
Richard
December 1, 2015 at 7:44 PM — ReplyHah! Got it guys.
I’ve decided to scroll through each sheet. In each sheet scroll through each Shape. If the Shape.Type = msoChart Then I can pick up the Alternative Text and act accordingly.Code extract:
For lShtCtr = 1 To ThisWorkbook.Sheets.Count
Debug.Print “Checking worksheet ” & lShtCtr & ” ” & Sheets(lShtCtr).Name & “. Detected ” & ThisWorkbook.Sheets(lShtCtr).Shapes.Count & ” shapes.”
For lShapeCtr = 1 To ThisWorkbook.Sheets(lShtCtr).Shapes.Count
If ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Type = msoChart Then
myText = ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).AlternativeText
Debug.Print “Alt Text in ” & ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Name & ” =:” & myText
If InStr(1, myText, “#AutoScale”, vbTextCompare) > 0 Then
Debug.Print “Scaling axes on ” & ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Name
Call ScaleAxes(ThisWorkbook.Sheets(lShtCtr), ThisWorkbook.Sheets(lShtCtr).Shapes(lShapeCtr).Name)
End If ‘myText contains #AutoScale
End If ‘Shape.Type = msoChart
Next lShapeCtr
Next lShtCtrThe debug.print allow you to see what is going on. I’ve used the magic key phrase ‘#AutoScale’ as my command
Thanks
RichardAlways learning
-
Krishnaprasad Menon
January 2, 2016 at 10:45 AM — ReplyVery nice tutorial.. Chart creating example file is not available on download… Kindly make it available
-
PNRao
January 2, 2016 at 11:38 PM — ReplyThanks for your valuable feedback and reporting an issue, we have fixed it.
Thanks-PNRao!
-
HS
March 19, 2016 at 5:12 PM — ReplyVery quickly this site will be famous amid all blogging and site-building
users, due to it’s good posts -
chris
May 9, 2016 at 1:05 AM — Replyi want to explode on a pie chart the piece with the max value. How can i do this? Also what if I have on a pie two pieces with the same max value? Thank you.
-
Nagaraju
July 1, 2016 at 12:17 PM — ReplyHi All,
I’m trying to open website through Vba code….It was done…I need small information that if need code how to search search any information in google and display.
Regards,
Nagu -
Salty
August 25, 2016 at 11:12 PM — ReplyHi
This comment relates to your Example 13, above, but may apply to all of the Chart.Type examples.
Using Excel 2016 on Windows 8, I had to change one line as follows:
From > Chart.Type = xlPie
To > Chart.Chart.Type = xlPie -
Salty
August 29, 2016 at 9:01 AM — ReplyHi
Sorry, I sent you a typo in my August 25 2016 comment. It should have said:
It should have said
To > Chart.ChartType = xlPie -
Raspreet Singh Jaggi
October 21, 2016 at 3:22 PM — ReplyYour codes are very much helpful Mr.PNRao.
-
Dwayne
November 29, 2016 at 10:01 AM — ReplyHi all,
That was quite a read! I’ve come away with many ideas for future spreadsheets..I do have one quick query, I’m using the following script to change the data range for a chart I’m using;
Sub RECPLINE()
ActiveSheet.ChartObjects(“Chart 1”).Activate
ActiveChart.SeriesCollection(1).Select
ActiveChart.SetSourceData Source:=Range(“=Data!$AR$3:$AW$31”)
End SubInstead of having 6 charts crammed into one screen, I aim to have one chart and 6 buttons to change the data range in the chart.
Everything works fine, but I have formatted the visual aspects of the chart to be more appealing. After saving and re-opening the spreadsheet, the first chart has kept the formatting, but all the other charts adopt the standard formatting when the data range is changed..Is there any way I can force the existing visual changes, or will I have to code the changes into the VBA script each time I change the data range?
Any help would be greatly appreciated!
Cheers,
Dwayne. -
Rommel Pastidio
January 29, 2018 at 1:47 PM — ReplyHi PNrao,
The codes here is very useful, for now I am creating excel with VBA for charting. can you help me with below inquiry?
1. if I plot a chart using VBA how can I add comment on the point (if out of specs)? -
anil reddy
March 28, 2019 at 5:47 PM — Replyhi PNrao
how to do data validation using vba
-
paulus
May 20, 2019 at 12:21 PM — Replyhow can i specify range for x-axis and for y-axis when coding for a line graph, and all my data in rows. for example row 1 is my x-axis and row 2 is my y-axis?
-
amol
June 3, 2019 at 4:29 PM — ReplysBody = ” ”
Can you please explain above code…
-
amol
June 3, 2019 at 4:30 PM — ReplyMid(sImgPath, InStrRev(sImgPath, “) + 1)
kindly explain the above code…
-
PNRao
July 4, 2019 at 6:10 PM — Reply
Sub ttt()'Let us say, you have the file path and name asigned to the variable
sImgPath = "C:MainFolderSubFolderYourFileName.xlsm"'You can extract the filename using the given code
Filename = Mid(sImgPath, InStrRev(sImgPath, ") + 1)'Explaination
'InStrRev function checks find the fist finding posing of the given string (") in the sImgPath from the right
'i.e; InStrRev(sImgPath, ") expression results the value 24 in the above code
'And the mid function will return the substing from the given starting positions
'.ie;Mid(sImgPath,24+1) returns the substing of sImgPath from the 25th position
'="YourFileName.xlsm"End Sub
-
PNRao
July 4, 2019 at 6:12 PM — ReplyThis will assign blank space to the sBody variable.
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
3 Realtime VBA Projects
with Source Code!
Go to Top
Excel VBA Charts
We can term charts as objects in VBA. Similar to the worksheet, we can also insert charts in VBA. First, we select the data and chart type we want for our data. Now, there are two different types of charts we provide. One is the embed chart, where the chart is in the same sheet of data. Another is known as the chart sheet, where the chart is in a separate data sheet.
In data analysis, visual effects are the key performance indicators of the person who has done the analysis. Visuals are the best way an analyst can convey their message. Since we are all Excel users, we usually spend considerable time analyzing the data and drawing conclusions with numbers and charts. Creating a chart is an art to master. We hope you have good knowledge of creating charts with excelIn Excel, a graph or chart lets us visualize information we’ve gathered from our data. It allows us to visualize data in easy-to-understand pictorial ways. The following components are required to create charts or graphs in Excel: 1 — Numerical Data, 2 — Data Headings, and 3 — Data in Proper Order.read more. This article will show you how to create charts using VBA coding.
Table of contents
- Excel VBA Charts
- How to Add Charts using VBA Code in Excel?
- #1 – Create Chart using VBA Coding
- #2 – Create a Chart with the Same Excel Sheet as Shape
- #3 – Code to Loop through the Charts
- #4 – Alternative Method to Create Chart
- Recommended Articles
- How to Add Charts using VBA Code in Excel?
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Charts (wallstreetmojo.com)
How to Add Charts using VBA Code in Excel?
You can download this VBA Charts Excel Template here – VBA Charts Excel Template
#1 – Create Chart using VBA Coding
To create any chart, we should have some numerical data. For this example, we are going to use the below sample data.
First, let us jump to the VBA editorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more.
Step 1: Start Sub Procedure.
Code:
Sub Charts_Example1() End Sub
Step 2: Define the variable as Chart.
Code:
Sub Charts_Example1() Dim MyChart As Chart End Sub
Step 3: Since the chart is an object variable, we need to Set it.
Code:
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add End Sub
The above code will add a new sheet as a chart sheet, not a worksheet.
Step 4: Now, we need to design the chart. Open With Statement.
Code:
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add With MyChart End With End Sub
Step 5: The first thing we need to do with the chart is to Set the source range by selecting the “Set Source Data” method.
Code:
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add With MyChart .SetSourceData End With End Sub
Step 6: We need to mention the source range. In this case, my source range is in the sheet named “Sheet1,” and the range is “A1 to B7”.
Code:
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add With MyChart .SetSourceData Sheets("Sheet1").Range("A1:B7") End With End Sub
Step 7: Next up, we need to select the kind of chart we are going to create. For this, we need to select the Chart Type property.
Code:
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add With MyChart .SetSourceData Sheets("Sheet1").Range("A1:B7") .ChartType = End With End Sub
Step 8: Here, we have a variety of charts. I am going to select the “xlColumnClustered” chart.
Code:
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add With MyChart .SetSourceData Sheets("Sheet1").Range("A1:B7") .ChartType = xlColumnClustered End With End Sub
Now let’s run the code using the F5 key or manually and see how the chart looks.
Step 9: Now, change other properties of the chart. To change the chart title, below is the code.
Like this, we have many properties and methods with charts. Use each one of them to see the impact and learn.
Sub Charts_Example1() Dim MyChart As Chart Set MyChart = Charts.Add With MyChart .SetSourceData Sheets("Sheet1").Range("A1:B7") .ChartType = xlColumnClustered .ChartTitle.Text = "Sales Performance" End With End Sub
#2 – Create a Chart with the Same Excel Sheet as Shape
We need to use a different technique to create the chart with the same worksheet (datasheet) as the shape.
Step 1: First, declare three object variables.
Code:
Sub Charts_Example2() Dim Ws As Worksheet Dim Rng As Range Dim MyChart As Object End Sub
Step 2: Then, set the worksheet reference.
Code:
Sub Charts_Example2() Dim Ws As Worksheet Dim Rng As Range Dim MyChart As Object Set Ws = Worksheets("Sheet1") End Sub
Step 3: Now, set the range object in VBARange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more
Code:
Sub Charts_Example2() Dim Ws As Worksheet Dim Rng As Range Dim MyChart As Object Set Ws = Worksheets("Sheet1") Set Rng = Ws.Range("A1:B7") End Sub
Step 4: Now, set the chart object.
Code:
Sub Charts_Example2() Dim Ws As Worksheet Dim Rng As Range Dim MyChart As Object Set Ws = Worksheets("Sheet1") Set Rng = Ws.Range("A1:B7") Set MyChart = Ws.Shapes.AddChart2 End Sub
Step 5: Now, as usual, we can design the chart using the “With” statement.
Code:
Sub Charts_Example2() Dim Ws As Worksheet 'To Hold Worksheet Reference Dim Rng As Range 'To Hold Range Reference in the Worksheet Dim MyChart As Object Set Ws = Worksheets("Sheet1") 'Now variable "Ws" is equal to the sheet "Sheet1" Set Rng = Ws.Range("A1:B7") 'Now variable "Rng" holds the range A1 to B7 in the sheet "Sheet1" Set MyChart = Ws.Shapes.AddChart2 'Chart will be added as Shape in the same worksheet With MyChart.Chart .SetSourceData Rng 'Since we already set the range of cells to be used for chart we have use RNG object here .ChartType = xlColumnClustered .ChartTitle.Text = "Sales Performance" End With End Sub
It will add the chart below.
#3 – Code to Loop through the Charts
Like how we look through sheets to change the name, insert values, and hide and unhide them. Similarly, we need to use the ChartObject property to loop through the charts.
The below code will loop through all the charts in the worksheet.
Code:
Sub Chart_Loop() Dim MyChart As ChartObject For Each MyChart In ActiveSheet.ChartObjects 'Enter the code here Next MyChart End Sub
#4 – Alternative Method to Create Chart
We can use the below alternative method to create charts. We can use the ChartObject. Add method to create the chart below is the example code.
It will also create a chart like the previous method.
Code:
Sub Charts_Example3() Dim Ws As Worksheet Dim Rng As Range Dim MyChart As ChartObject Set Ws = Worksheets("Sheet1") Set Rng = Ws.Range("A1:B7") Set MyChart = Ws.ChartObjects.Add(Left:=ActiveCell.Left, Width:=400, Top:=ActiveCell.Top, Height:=200) MyChart.Chart.SetSourceData Source:=Rng MyChart.Chart.ChartType = xlColumnStacked MyChart.Chart.ChartTitle.Text = "Sales Performance" End Sub
Recommended Articles
This article has been a guide to VBA Charts. Here, we learn how to create a chart using VBA code, practical examples, and a downloadable template. Below you can find some useful Excel VBA articles: –
- Excel VBA Pivot Table
- What are Control Charts in Excel?
- Top 8 Types of Charts in Excel
- Graphs vs. Charts – Compare
In this Article
- Creating an Embedded Chart Using VBA
- Specifying a Chart Type Using VBA
- Adding a Chart Title Using VBA
- Changing the Chart Background Color Using VBA
- Changing the Chart Plot Area Color Using VBA
- Adding a Legend Using VBA
- Adding Data Labels Using VBA
- Adding an X-axis and Title in VBA
- Adding a Y-axis and Title in VBA
- Changing the Number Format of An Axis
- Changing the Formatting of the Font in a Chart
- Deleting a Chart Using VBA
- Referring to the ChartObjects Collection
- Inserting a Chart on Its Own Chart Sheet
Excel charts and graphs are used to visually display data. In this tutorial, we are going to cover how to use VBA to create and manipulate charts and chart elements.
You can create embedded charts in a worksheet or charts on their own chart sheets.
Creating an Embedded Chart Using VBA
We have the range A1:B4 which contains the source data, shown below:
You can create a chart using the ChartObjects.Add method. The following code will create an embedded chart on the worksheet:
Sub CreateEmbeddedChartUsingChartObject()
Dim embeddedchart As ChartObject
Set embeddedchart = Sheets("Sheet1").ChartObjects.Add(Left:=180, Width:=300, Top:=7, Height:=200)
embeddedchart.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B4")
End Sub
The result is:
You can also create a chart using the Shapes.AddChart method. The following code will create an embedded chart on the worksheet:
Sub CreateEmbeddedChartUsingShapesAddChart()
Dim embeddedchart As Shape
Set embeddedchart = Sheets("Sheet1").Shapes.AddChart
embeddedchart.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B4")
End Sub
Specifying a Chart Type Using VBA
We have the range A1:B5 which contains the source data, shown below:
You can specify a chart type using the ChartType Property. The following code will create a pie chart on the worksheet since the ChartType Property has been set to xlPie:
Sub SpecifyAChartType()
Dim chrt As ChartObject
Set chrt = Sheets("Sheet1").ChartObjects.Add(Left:=180, Width:=270, Top:=7, Height:=210)
chrt.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B5")
chrt.Chart.ChartType = xlPie
End Sub
The result is:
These are some of the popular chart types that are usually specified, although there are others:
- xlArea
- xlPie
- xlLine
- xlRadar
- xlXYScatter
- xlSurface
- xlBubble
- xlBarClustered
- xlColumnClustered
Adding a Chart Title Using VBA
We have a chart selected in the worksheet as shown below:
You have to add a chart title first using the Chart.SetElement method and then specify the text of the chart title by setting the ChartTitle.Text property.
The following code shows you how to add a chart title and specify the text of the title of the Active Chart:
Sub AddingAndSettingAChartTitle()
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = "The Sales of the Product"
End Sub
The result is:
Note: You must select the chart first to make it the Active Chart to be able to use the ActiveChart object in your code.
Changing the Chart Background Color Using VBA
We have a chart selected in the worksheet as shown below:
You can change the background color of the entire chart by setting the RGB property of the FillFormat object of the ChartArea object. The following code will give the chart a light orange background color:
Sub AddingABackgroundColorToTheChartArea()
ActiveChart.ChartArea.Format.Fill.ForeColor.RGB = RGB(253, 242, 227)
End Sub
The result is:
You can also change the background color of the entire chart by setting the ColorIndex property of the Interior object of the ChartArea object. The following code will give the chart an orange background color:
Sub AddingABackgroundColorToTheChartArea()
ActiveChart.ChartArea.Interior.ColorIndex = 40
End Sub
The result is:
Note: The ColorIndex property allows you to specify a color based on a value from 1 to 56, drawn from the preset palette, to see which values represent the different colors, click here.
Changing the Chart Plot Area Color Using VBA
We have a chart selected in the worksheet as shown below:
You can change the background color of just the plot area of the chart, by setting the RGB property of the FillFormat object of the PlotArea object. The following code will give the plot area of the chart a light green background color:
Sub AddingABackgroundColorToThePlotArea()
ActiveChart.PlotArea.Format.Fill.ForeColor.RGB = RGB(208, 254, 202)
End Sub
The result is:
Adding a Legend Using VBA
We have a chart selected in the worksheet, as shown below:
You can add a legend using the Chart.SetElement method. The following code adds a legend to the left of the chart:
Sub AddingALegend()
ActiveChart.SetElement (msoElementLegendLeft)
End Sub
The result is:
You can specify the position of the legend in the following ways:
- msoElementLegendLeft – displays the legend on the left side of the chart.
- msoElementLegendLeftOverlay – overlays the legend on the left side of the chart.
- msoElementLegendRight – displays the legend on the right side of the chart.
- msoElementLegendRightOverlay – overlays the legend on the right side of the chart.
- msoElementLegendBottom – displays the legend at the bottom of the chart.
- msoElementLegendTop – displays the legend at the top of the chart.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Adding Data Labels Using VBA
We have a chart selected in the worksheet, as shown below:
You can add data labels using the Chart.SetElement method. The following code adds data labels to the inside end of the chart:
Sub AddingADataLabels()
ActiveChart.SetElement msoElementDataLabelInsideEnd
End Sub
The result is:
You can specify how the data labels are positioned in the following ways:
- msoElementDataLabelShow – display data labels.
- msoElementDataLabelRight – displays data labels on the right of the chart.
- msoElementDataLabelLeft – displays data labels on the left of the chart.
- msoElementDataLabelTop – displays data labels at the top of the chart.
- msoElementDataLabelBestFit – determines the best fit.
- msoElementDataLabelBottom – displays data labels at the bottom of the chart.
- msoElementDataLabelCallout – displays data labels as a callout.
- msoElementDataLabelCenter – displays data labels on the center.
- msoElementDataLabelInsideBase – displays data labels on the inside base.
- msoElementDataLabelOutSideEnd – displays data labels on the outside end of the chart.
- msoElementDataLabelInsideEnd – displays data labels on the inside end of the chart.
Adding an X-axis and Title in VBA
We have a chart selected in the worksheet, as shown below:
You can add an X-axis and X-axis title using the Chart.SetElement method. The following code adds an X-axis and X-axis title to the chart:
Sub AddingAnXAxisandXTitle()
With ActiveChart
.SetElement msoElementPrimaryCategoryAxisShow
.SetElement msoElementPrimaryCategoryAxisTitleHorizontal
End With
End Sub
The result is:
Adding a Y-axis and Title in VBA
We have a chart selected in the worksheet, as shown below:
You can add a Y-axis and Y-axis title using the Chart.SetElement method. The following code adds an Y-axis and Y-axis title to the chart:
Sub AddingAYAxisandYTitle()
With ActiveChart
.SetElement msoElementPrimaryValueAxisShow
.SetElement msoElementPrimaryValueAxisTitleHorizontal
End With
End Sub
The result is:
VBA Programming | Code Generator does work for you!
Changing the Number Format of An Axis
We have a chart selected in the worksheet, as shown below:
You can change the number format of an axis. The following code changes the number format of the y-axis to currency:
Sub ChangingTheNumberFormat()
ActiveChart.Axes(xlValue).TickLabels.NumberFormat = "$#,##0.00"
End Sub
The result is:
Changing the Formatting of the Font in a Chart
We have the following chart selected in the worksheet as shown below:
You can change the formatting of the entire chart font, by referring to the font object and changing its name, font weight, and size. The following code changes the type, weight and size of the font of the entire chart.
Sub ChangingTheFontFormatting()
With ActiveChart
.ChartArea.Format.TextFrame2.TextRange.Font.Name = "Times New Roman"
.ChartArea.Format.TextFrame2.TextRange.Font.Bold = True
.ChartArea.Format.TextFrame2.TextRange.Font.Size = 14
End With
The result is:
Deleting a Chart Using VBA
We have a chart selected in the worksheet, as shown below:
We can use the following code in order to delete this chart:
Sub DeletingTheChart()
ActiveChart.Parent.Delete
End Sub
Referring to the ChartObjects Collection
You can access all the embedded charts in your worksheet or workbook by referring to the ChartObjects collection. We have two charts on the same sheet shown below:
We will refer to the ChartObjects collection in order to give both charts on the worksheet the same height, width, delete the gridlines, make the background color the same, give the charts the same plot area color and make the plot area line color the same color:
Sub ReferringToAllTheChartsOnASheet()
Dim cht As ChartObject
For Each cht In ActiveSheet.ChartObjects
cht.Height = 144.85
cht.Width = 246.61
cht.Chart.Axes(xlValue).MajorGridlines.Delete
cht.Chart.PlotArea.Format.Fill.ForeColor.RGB = RGB(242, 242, 242)
cht.Chart.ChartArea.Format.Fill.ForeColor.RGB = RGB(234, 234, 234)
cht.Chart.PlotArea.Format.Line.ForeColor.RGB = RGB(18, 97, 172)
Next cht
End Sub
The result is:
Inserting a Chart on Its Own Chart Sheet
We have the range A1:B6 which contains the source data, shown below:
You can create a chart using the Charts.Add method. The following code will create a chart on its own chart sheet:
Sub InsertingAChartOnItsOwnChartSheet()
Sheets("Sheet1").Range("A1:B6").Select
Charts.Add
End Sub
The result is:
See some of our other charting tutorials:
Charts in Excel
Create a Bar Chart in VBA
Программное создание графика (диаграммы) в VBA Excel с помощью метода Charts.Add на основе данных из диапазона ячеек на рабочем листе. Примеры.
Метод Charts.Add
В настоящее время на сайте разработчиков описывается метод Charts.Add2, который, очевидно, заменил метод Charts.Add. Тесты показали, что Charts.Add продолжает работать в новых версиях VBA Excel, поэтому в примерах используется именно он.
Синтаксис
Charts.Add ([Before], [After], [Count]) |
Charts.Add2 ([Before], [After], [Count], [NewLayout]) |
Параметры
Параметры методов Charts.Add и Charts.Add2:
Параметр | Описание |
---|---|
Before | Имя листа, перед которым добавляется новый лист с диаграммой. Необязательный параметр. |
After | Имя листа, после которого добавляется новый лист с диаграммой. Необязательный параметр. |
Count | Количество добавляемых листов с диаграммой. Значение по умолчанию – 1. Необязательный параметр. |
NewLayout | Если NewLayout имеет значение True, диаграмма вставляется с использованием новых правил динамического форматирования (заголовок имеет значение «включено», а условные обозначения – только при наличии нескольких рядов). Необязательный параметр. |
Если параметры Before и After опущены, новый лист с диаграммой вставляется перед активным листом.
Примеры
Таблицы
В качестве источников данных для примеров используются следующие таблицы:
Пример 1
Программное создание объекта Chart с типом графика по умолчанию и по исходным данным из диапазона «A2:B26»:
Sub Primer1() Dim myChart As Chart ‘создаем объект Chart с расположением нового листа по умолчанию Set myChart = ThisWorkbook.Charts.Add With myChart ‘назначаем объекту Chart источник данных .SetSourceData (Sheets(«Лист1»).Range(«A2:B26»)) ‘переносим диаграмму на «Лист1» (отдельный лист диаграммы удаляется) .Location xlLocationAsObject, «Лист1» End With End Sub |
Результат работы кода VBA Excel из первого примера:
Пример 2
Программное создание объекта Chart с двумя линейными графиками по исходным данным из диапазона «A2:C26»:
Sub Primer2() Dim myChart As Chart Set myChart = ThisWorkbook.Charts.Add With myChart .SetSourceData (Sheets(«Лист1»).Range(«A2:C26»)) ‘задаем тип диаграммы (линейный график с маркерами) .ChartType = xlLineMarkers .Location xlLocationAsObject, «Лист1» End With End Sub |
Результат работы кода VBA Excel из второго примера:
Пример 3
Программное создание объекта Chart с круговой диаграммой, разделенной на сектора, по исходным данным из диапазона «E2:F7»:
Sub Primer3() Dim myChart As Chart Set myChart = ThisWorkbook.Charts.Add With myChart .SetSourceData (Sheets(«Лист1»).Range(«E2:F7»)) ‘задаем тип диаграммы (пирог — круг, разделенный на сектора) .ChartType = xlPie ‘задаем стиль диаграммы (с отображением процентов) .ChartStyle = 261 .Location xlLocationAsObject, «Лист1» End With End Sub |
Результат работы кода VBA Excel из третьего примера:
Примечание
В примерах использовались следующие методы и свойства объекта Chart:
Компонент | Описание |
---|---|
Метод SetSourceData | Задает диапазон исходных данных для диаграммы. |
Метод Location | Перемещает диаграмму в заданное расположение (новый лист, существующий лист, элемент управления). |
Свойство ChartType | Возвращает или задает тип диаграммы. Смотрите константы. |
Свойство ChartStyle | Возвращает или задает стиль диаграммы. Значение нужного стиля можно узнать, записав макрос. |
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!
VBA Chart Guide Contents
-
Create/Insert Chart
-
Looping Through Charts/Series
-
Chart Title (Adding/Modifying)
-
Chart Legend (Adding/Modifying)
-
Adding Various Chart Attributes
-
Modifying Various Chart Attributes
-
Removing Various Chart Attributes
-
Change Chart Colors
-
Chart Excel Add-ins
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
Sub CreateChart()
‘PURPOSE: Create a chart (chart dimensions are required)
Dim rng As Range
Dim cht As ChartObject
‘Your data range for the chart
Set rng = ActiveSheet.Range(«A24:M27»)
‘Create a chart
Set cht = ActiveSheet.ChartObjects.Add( _
Left:=ActiveCell.Left, _
Width:=450, _
Top:=ActiveCell.Top, _
Height:=250)
‘Give chart some data
cht.Chart.SetSourceData Source:=rng
‘Determine the chart type
cht.Chart.ChartType = xlXYScatterLines
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
‘Loop through all series in a chart
For Each ser In grph.Chart.SeriesCollection
Next ser
‘Loop Through all series on Activesheet
For Each cht In ActiveSheet.ChartObjects
For Each ser In grph.Chart.SeriesCollection
Next ser
Next cht
End Sub
Adding & Modifying A Chart Title
Add Chart Title
Sub AddChartTitle()
‘PURPOSE: Add a title to a specific chart
Dim cht As ChartObject
Set cht = ActiveSheet.ChartObjects(«Chart 1»)
‘Ensure chart has a title
cht.Chart.HasTitle = True
‘Change chart’s title
cht.Chart.ChartTitle.Text = «My Graph»
End Sub
Move/Reposition Chart Title
Sub RepositionChartTitle()
‘PURPOSE: Reposition a chart’s title
Dim cht As ChartObject
Set cht = ActiveSheet.ChartObjects(«Chart 1»)
‘Reposition title
With cht.Chart.ChartTitle
.Left = 100
.Top = 50
End With
End Sub
Adding & Modifying A Graph Legend
Insert/Create Chart 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)
‘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
Resize/Move Chart Legend
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()
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 Chart 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
Chart Excel Add-ins
-
Waterfall Chart Excel Add-in — Automatically create editable Waterfall Charts directly in your spreadsheet.
-
AutoChart Excel Add-in — This add-in will allow you to create, manipulate series ranges, and format all your charts at once. Making adjustments has never been easier!
-
myBrand Excel Add-in — Stores your favorite colors to the Excel Ribbon and allows you to color cells, shapes, and charts.
-
Peltier Tech Charts for Excel — A chart-building toolkit with the automated creation of difficult chart builds such as Histograms, Pareto, Marimekko, and many more.
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!
About The Author
Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.
Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!
— Chris
Founder, TheSpreadsheetGuru.com
Charts in Excel VBA — Add a Chart, the Chart object & the ChartObject object
Contents:
Worksheet & Chart Sheet in Excel
Add a Chart
ChartObject object
Chart object
Excel is a great tool to create charts quickly & easily, to display worksheet data in a meaningful manner for users. This section illustrates creating & manipulating charts with vba code, in excel. You have a variety of chart types in Excel, such as Column, Bar, Line, Stacked (column, bar, line, …), Pie, XYScatter & Bubble charts which are the most common. Using VBA, you can manipulate embedded charts (which are embedded or placed within a worksheet & and can be displayed alongwith their source data or other information) or a chart sheet (a separate sheet in the workbook which contains only a chart and does not display the source data or any other information). Our emphasis is more on embedded charts in this section.
Column & Bar charts (clustered or otherwise) are useful for comparison between items & to display data changes over a period of time at specified time intervals. Line charts are useful for comparison between items & to display continuous data over time & display data trends at equal time intervals. Stacked charts (column, bar, line, etc) compare an individual item’s contribution to the whole, across categories or time intervals. A Pie chart is particularly useful where relative percentages are required to be displayed. An XYScatter chart is particularly useful for comparing numerical data wherein values are not spaced evenly at regular intervals and you want to compare and show relationships by grouping sets of values by disregarding the time factor or interval. Bubble charts are similar to XY Scatter charts, except that bubble charts compare 3 sets of values instead of two sets of values compared in scatter charts, where the third value determines the size of the marker where the 2 values intersect in scatter charts.
This chapter discusses the overall concept of charts & creating them — the Chart Object that represents a chart in a workbook which can be either an embedded chart or a separate chart sheet, how to add a chart and refer to charts with index number or name. We explain in detail the Chart object & the ChartObject object and using their properties & methods.
Note: In this topic, while specifying Syntax for a property or method of an object, the prefix obj has been used to indicate an object variable viz. for the ChartArea property of the chart object, the Syntax used is: objChart.ChartArea, wherein objChart indicates a Chart object variable. Further, to keep the topic compact, with reference to objects, not all properties or methods may have been mentioned but only some common or often used ones.
Worksheet & Chart Sheet in Excel
The Worksheet Object represents a single worksheet in a workbook. The Worksheets Object refers to a collection of all worksheets in a workbook.
The Sheets Object refers to a collection of all sheets (ie. all worksheets, chart sheets, macro sheets & dialog sheets) in a workbook. The Worksheet Object is a member of both the Worksheets collection (Worksheets object) and the Sheets collection (Sheets object). The Workbook.Worksheets Property returns a Worksheets collection (ie. a Worksheets object) which refers to all worksheets in a workbook. The Workbook.Sheets Property returns a Sheets collection (ie. a Sheets object) which refers to all sheets in a workbook. Using the code MsgBox ActiveWorkbook.Worksheets.Count will return the number of worksheets in the active workbook, and the code MsgBox ActiveWorkbook.Sheets.Count will return the number of sheets in the active workbook.
A workbook can contain 4 types of sheets — worksheet, chart sheet, macro sheet (MS Excel 4.0 Macro sheet) and a dialog sheet (MS Excel 5.0 Dialog sheet). Macro sheets (also called XLM macros) & dialog sheets (used in earlier Excel versions to create customized dialog boxes / making forms, now replaced by UserForms), are still being provided & supported in Excel 2007 only for backward compatibility with earlier versions of Microsoft Excel. A macro sheet (or a dialog sheet) is not included as a part of the Worksheets collection but is a part of the Sheets collection.
Chart objects in VBA
The Chart Object represents a chart (single chart) in a workbook — a chart can be either an embedded chart or a separate chart sheet.
The Charts collection, ie. the Charts Object, refers to a collection of all chart sheets in a workbook, and excludes all embedded charts — each chart sheet is represented by a Chart object. Workbook.Charts Property — the Charts property of the Workbook object returns all chart sheets (ie. the Charts collection) in the specified workbook (Syntax: objWorkbook.Charts). A Chart Sheet contains a single chart and covers the entire worksheet. The Add method of the Charts object is used to add or create a new chart sheet, as explained later.
Charts.Item Property: The Item Property of the Charts object (collection of all chart sheets in a workbook excluding embedded charts) refers to a single chart object in a collection. Syntax: objCharts.Item(Index), where Index is the chart sheet name or index number. You can also omit using the ‘item’ word, using syntax of objCharts(ChartName) or objCharts(IndexNumber) ie. use objCharts(Index) where Index is the chart sheet name or index number viz. Charts(«Chart1») or Charts(1). The index number starts at 1 for the first or leftmost chart sheet on the workbook tab bar and increments accordingly for each chart sheet moving towards the right (hidden chart sheets are also included), the last (rightmost) chart sheet being returned by Charts(Charts.Count). The Count property of the Charts object — objCharts.Count — returns the number of charts (chart sheets) in the collection (ie. in the workbook).
The chart sheet tab displays the name of the chart sheet. Use the Name property of the Chart object to set or return the name of a chart sheet. Syntax: objChart.Name. This property is read only for a Chart object (embedded chart), read-write for a ChartObject (embedded chart), and read-write for a Chart object (chart sheet).
The ChartObject object represents an embedded chart (single embedded chart) in a sheet. The ChartObjects object refers to a collection of all ChartObject objects (ie. embedded charts) in a single sheet (ie. in a specified chart sheet, dialog sheet or worksheet). Worksheet.ChartObjects Method — the ChartObjects method of the Worksheet object returns either: (i) a single embedded chart (a ChartObject object) — Worksheets(«Sheet1»).ChartObjects(1); or (ii) a collection of all embedded charts (ie. the ChartObjects object) — Worksheets(«Sheet1»).ChartObjects; in the specified workbook. The ChartObject object acts as a container for a Chart object — using the Chart Property of the ChartObject returns a Chart object which refers to a chart contained in the ChartObject object — Worksheets(«Sheet1»).ChartObjects(1).Chart.
Use the ChartObjects.Item Method — Syntax: objChartObjects.Item(Index) — to return a single ChartObject object, where index is the index number or name of the embedded chart. The ChartObjects.Count Property returns the number of embedded charts (ChartObject objects) in the collection (ie. ChartObjects collection).
The Name property of the ChartObject — Syntax: objChartObject.Name — is used to set or return the name of the ChartObject. The Add method of the ChartObjects object is used to create or add a new embedded chart, as explained later.
Example: Using Sheets, Worksheets, Charts & Embedded Charts in vba
Sub Sheets_Charts()
‘Using Sheets, Worksheets, Charts & Embedded Charts in vba
‘Consider a workbook with 4 sheets in the order: «Sheet1», «Chart1», «Sheet2», «Sheet3» & «Chart2» ie. 3 worksheets & 2 Chart Sheets
‘»Sheet1″ has 2 embedded charts
‘——————————
Dim ws As Worksheet
‘returns 3 (3 worksheets — «Sheet1», «Sheet2» & «Sheet3»):
MsgBox ThisWorkbook.Worksheets.Count
‘returns the names of each of the 3 worksheets — «Sheet1», «Sheet2» & «Sheet3»:
For Each ws In ThisWorkbook.Worksheets
MsgBox ws.Name
Next
‘——————————
Dim obj As Object, i As Integer
‘returns 5 — 3 worksheets & 2 chart sheets:
MsgBox ThisWorkbook.Sheets.Count
‘returns the names of each of the 5 sheets — «Sheet1», «Chart1», «Sheet2» & «Sheet3» & «Chart2»:
For i = 1 To ThisWorkbook.Sheets.Count
MsgBox ThisWorkbook.Sheets(i).Name
Next i
‘returns the names of each of the 5 sheets — «Sheet1», «Chart1», «Sheet2» & «Sheet3» & «Chart2»:
For Each obj In ThisWorkbook.Sheets
MsgBox obj.Name
Next
‘returns the names of each of the 3 worksheets («Sheet1», «Sheet2» & «Sheet3»):
For Each obj In ThisWorkbook.Worksheets
MsgBox obj.Name
Next
‘——————————
‘returns 2 — there are 2 chart objects (chart sheets «Chart1» & «Chart2») in this workbook:
MsgBox ThisWorkbook.Charts.Count
‘returns «Chart1», the first chart sheet in the workbooks tab bar
MsgBox Charts(1).Name
‘returns «Chart2», the last sheet in the workbooks tab bar, which is a Chart Sheet — Sheets Object refers to a collection of all sheets, including chart sheets
MsgBox Sheets(5).Name
‘Change the name of «Chart2» to «ChartNew»
Charts(2).Name = «ChartNew«
‘returns «ChartNew», the second chart sheet in the workbooks tab bar
MsgBox Charts(2).Name
‘——————————
‘returns 0 — there is no embedded chart (ChartObject Object) in the chart sheet:
MsgBox Sheets(«Chart1»).ChartObjects.Count
‘returns 2 — there are 2 embedded charts (ChartObject Objects) in the worksheet named «Sheet1»:
MsgBox Sheets(«Sheet1»).ChartObjects.Count
‘Change the name of the second embedded chart in «Sheet1» to «EmbChart2»
Sheets(«Sheet1»).ChartObjects(2).Name = «EmbChart2«
‘returns «EmbChart2», the second embedded chart in «Sheet1»
MsgBox Sheets(«Sheet1»).ChartObjects(2).Name
End Sub
Add a Chart
Charts.Add Method: Use the Add method of the Charts object to add or create a new chart sheet. Syntax: objCharts.Add(Before, After, Count, Type). All the 4 arguments are optional. Before & After arguments refer to the sheet before or after which the new chart sheet is to be added — if both these are omitted, the new chart is by default added before the active sheet. The Count argument refers to the number of chart sheets to be added, default being one. The Type argument refers to the type of chart to be added, as per the XlChartType constant — note that not all chart types are available for PivotChart reports.
Some examples of XlChartType Enumeration: xlAreaStacked (value 76) — Stacked Area; xlBarClustered (57) — Clustered Bar; xlBarOfPie (71) — Bar of Pie; xlBarStacked (58) — Stacked Bar; xlColumnClustered (51) — Clustered Column; xlColumnStacked (52) — Stacked Column; xlConeBarClustered (102) — Cone Bar Clustered; xlConeBarStacked (103) — Cone Bar Stacked; xlCylinderBarClustered (95) — Clustered Cylinder Bar; xlCylinderBarStacked (96) — Stacked Cylinder Bar; xlLine (4) — Line; xlLineMarkers (65) — Line with Markers; xlLineStacked (63) — Stacked Line; xlPie (5) — Pie; xlPieOfPie (68) — Pie of Pie; xlPieExploded (69) — Exploded Pie; xlXYScatter (-4169) — Scatter; xlXYScatterLines (74) — Scatter with Lines; xl3DArea (-4098) — 3D Area; xl3DColumn (-4100) — 3D Column; xl3DAreaStacked (78) — 3D Stacked Area; xl3DBarClustered (60) — 3D Clustered Bar; xl3DBarStacked (61) — 3D Stacked Bar; xl3DPie (-4102) — 3D Pie; xl3DPieExploded (70) 3D Pie Exploded; … and so on.
ChartObjects.Add Method: Use the Add method of the ChartObjects object, to create or add a new embedded chart. Syntax: objChartObjects.Add(Left, Top, Width, Height). The Left & Top arguments specify the coordinates relative to the top & left (respectively) corner of cell A1 in a worksheet. The Width & Height arguments specify the size in points. All arguments are necessary to specify.
As explained above, the Chart Object represents a chart (single chart) in a workbook — a chart can be either an embedded chart or a separate chart sheet. Code to return a Chart object which is contained in the first embedded chart, named «EmbChart», in Sheet1: Sheets(«Sheet1»).ChartObjects(1).Chart or Sheets(«Sheet1»).ChartObjects(«»EmbChart»,»).Chart. Code to return a Chart object (vba code) which is the first Chart sheet, named «ChSheet»: Charts(«ChSheet») or Charts(1).
Example: Return a Chart object; use the Chart Type property with the Chart object
Sub ChartObj_ChartType()
‘Return a Chart object; use the Chart Type property of the Chart object
‘using the Chart Property of the ChartObject returns a Chart object which is contained in the first embedded chart, named «EmbChart», in Sheet1
‘use the ChartType property of the Chart object: returns -4100, indicating a ‘xl3DColumn’ chart type
MsgBox Sheets(«Sheet1»).ChartObjects(1).Chart.ChartType
MsgBox Sheets(«Sheet1»).ChartObjects(«EmbChart»).Chart.ChartType
‘use the Item Property of the Charts object to return a single chart object in a collection — returns a Chart object which is the first Chart sheet, named «ChSheet»
‘use the ChartType property of the Chart object: returns 51, indicating a ‘Clustered Column’ chart type
MsgBox Charts(«ChSheet»).ChartType
MsgBox Charts(1).ChartType
End Sub
Example: Create a new chart sheet
Sub ChartSheet_New()
‘create a new chart sheet
‘Add method of the Charts object adds a new empty chart sheet with a default name and places it immediately before the last sheet in the active workbook
ActiveWorkbook.Charts.Add Before:=Sheets(Sheets.Count)
‘the new chart sheet becomes the active chart
With ActiveChart
‘set type of chart
.ChartType = xlColumnClustered
‘set the range of source data for the chart
.SetSourceData Source:=Sheets(«Sheet1»).Range(«A1:D6»)
‘rename the new chart sheet
.Name = «NewChartSheet«
‘moves the chart sheet to a new location and places after the last sheet in the workbook
.Move After:=Sheets(Sheets.Count)
End With
End Sub
Example: Create a new embedded chart & move to a new location — refer Images 1a (Source Data) & 1b (Embedded Chart)
Sub EmbeddedChart_New()
‘create a new embedded chart & move to a new location — refer Images 1a (Source Data) & 1b (Embedded Chart)
Dim rngSourceData As Range
Set rngSourceData = Sheets(«Sheet2»).Range(«A1:D6»)
‘declare a ChartObject
Dim oChObj As ChartObject
‘the Add method of the ChartObjects object is used to create a new empty embedded chart and add it to the collection in the active sheet
Set oChObj = ActiveSheet.ChartObjects.Add(Left:=25, Width:=300, Top:=10, Height:=225)
With oChObj.Chart
‘set type of chart
.ChartType = xlColumnClustered
‘set the range of source data for the chart — refer Image 1a
.SetSourceData Source:=rngSourceData, PlotBy:=xlColumns
‘move the embedded chart to a new location — to sheet named «Sheet4»
‘the Name argument is required to specify the sheet where to embed a new chart, because the Where argument mentions xlLocationAsObject
.Location Where:=xlLocationAsObject, Name:=»Sheet4«
End With
‘moves the embedded chart (presuming it to be the first ChartObject in «Sheet4») to a new chart sheet created with the name «StudentMarks»
‘the Name argument is not necessary because the Where argument mentions xlLocationAsNewSheet — if the Name argument is omitted, a new chart sheet is created with the default name
Sheets(«Sheet4″).ChartObjects(1).Chart.Location Where:=xlLocationAsNewSheet, Name:=»StudentMarks«
End Sub
Example: Looping through all embedded charts within a worksheet
‘looping through all embedded charts within a worksheet
Dim oChObj As ChartObject
With ActiveSheet
If .ChartObjects.count > 0 Then
MsgBox «There are » & .ChartObjects.count & » Embedded Charts in Active Sheet, with the names:»
For Each oChObj In .ChartObjects
With oChObj
MsgBox .Name
End With
Next
Else
MsgBox «There is no Embedded Chart in Active Sheet»
End If
End With
ChartObject object
Commonly used Properties of the ChartObject object: |
||
Property | Syntax | Description |
Chart Property | objChartObject.Chart |
The ChartObject object acts as a container for a Chart object — using the Chart Property of the ChartObject returns a Chart object which refers to a chart contained in the ChartObject object viz. return a Chart object: Sheets(«Sheet1»).ChartObjects(1).Chart Then use the ChartType Property of the Chart object to set chart type of «Line with Markers»: Sheets(«Sheet1»).ChartObjects(1).Chart.ChartType = xlLineMarkers |
Height Property | objChartObject.Height | Sets or returns the height, in points, of the embedded chart. |
Width Property | objChartObject.Width | Sets or returns the width, in points, of the embedded chart. |
Left Property | objChartObject.Left |
Sets or returns the distance, in points, from the left edge of the embedded chart to the left edge of column A on a worksheet. Ex. Align the left edge of the embedded chart with the left edge of the worksheet’s column C: Sheets(1).ChartObjects(1).Left = Sheets(1).Columns(«C»).Left |
Top Property | objChartObject.Top | Sets or returns the distance, in points, from the top edge of the embedded chart to the top of row 1 on a worksheet |
Name Property | objChartObject.Name | Sets or returns the name of the embedded chart, as a string value. |
RoundedCorners Property | objChartObject.RoundedCorners | sets or returns a Boolean value determining if the embedded chart has rounded corners or not — True indicates rounded corners. |
Shadow Property | objChartObject.Shadow | sets or returns a Boolean value determining if the embedded chart has a shadow or not |
TopLeftCell Property | objChartObject.TopLeftCell |
Returns the address of the cell which is under the upper-left corner of the embedded chart. This property returns a Range object, & is read-only. Ex: MsgBox Sheets(«Sheet1»).ChartObjects(1).TopLeftCell.Address |
BottomRightCell Property | objChartObject.BottomRightCell |
Returns the address of the cell which is under the lower-right corner of the embedded chart. This property returns a Range object, & is read-only. Ex: MsgBox Sheets(«Sheet1»).ChartObjects(1).BottomRightCell.Address |
Locked Property | objChartObject.Locked | Sets or returns a Boolean value, which is True if the embedded chart is locked and False indicating that the embedded chart can be modified on a protected sheet. |
Placement Property | objChartObject.Placement |
Sets or returns a value (an XlPlacement constant) which refers to how the embedded chart is attached to its underlying cells. XlPlacement constants: xlMoveAndSize (value 1) indicates that the embedded chart is moved & sized with the cells; xlMove (value 2) indicates that the embedded chart is moved with the cells; xlFreeFloating (value 3) indicates that the embedded chart is free floating and is not moved or sized with its underlying cells. |
ShapeRange Property | objChartObject.ShapeRange | Returns (read-only) a ShapeRange object representing a shape range. A Shape Range (ie. ShapeRange Object) is a set of shapes, and it can represent either a specified subset of shapes (say shape 1 & shape 3), or can represent all selected shapes on a document. A set of shapes can be returned by specifying an Index Number or Name viz. Shapes.Range(index), where index is the index number or name, and you can also use the Range property & the Array function to build an array of index numbers (or names) to return specific number of shapes — refer below example. |
Sub Chart_ShapeRange() ‘refer sheet «Sheet1» which contains 5 shapes: 4 are embedded charts, out of which 3 charts are of type xl3DColumn (value -4100), and 1 is an oval shape Dim shp As Shape ‘————————— Dim objChtObjShpRng As ShapeRange ‘create a shape range representing all embedded charts in «Sheet1» Set objChtObjShpRng = Sheets(«Sheet1»).ChartObjects.ShapeRange ‘returns names of all 4 charts For Each shp In objChtObjShpRng MsgBox shp.Name Next shp ‘returns names of 3 charts which are of type xl3DColumn (value -4100) For Each shp In objChtObjShpRng If shp.Chart.ChartType = -4100 Then MsgBox shp.Name End If Next shp ‘————————— Dim objShpRng As ShapeRange ‘use the Range property, & the Array function, to build an array of index numbers (or names), to return specific number of shapes Set objShpRng = Sheets(«Sheet1»).Shapes.Range(Array(1, 3, 5)) ‘returns names of 2 charts (chart 1 & 3), and the oval shape For Each shp In objShpRng MsgBox shp.Name Next shp ‘————————— Dim obj As Object ‘create a ShapeRange object representing all shapes in «Sheet1» ‘select all shapes in «Sheet1» & use the ShapeRange property of the Selection object to create a ShapeRange object containing all shapes Sheets(«Sheet1»).Activate Sheets(«Sheet1»).Shapes.SelectAll ‘using the ShapeRange property of the Selection object to return all shapes in the selection Set objShpRng = Selection.ShapeRange ‘returns names of all 5 shapes, including the 4 charts For Each obj In objShpRng MsgBox obj.Name Next obj End Sub |
||
Visible Property | objChartObject.Visible |
Set or return a Boolean value which determines whether the embedded chart is visible or not Ex. For the embedded chart to be visible: Sheets(«Sheet1»).ChartObjects(1).Visible = True |
Commonly used Methods of the ChartObject Object: |
||
Method | Syntax | Description |
Activate Method | objChartObject.Activate | Activates an embedded chart and makes it the active chart — refer the Activate Method of the Chart object where this has been explained in detail. |
Copy Method | objChartObject.Copy | Copies the embedded chart to the Clipboard. |
Cut Method | objChartObject.Cut | Cuts the embedded chart to the Clipboard. Refer below code to copy or cut an embedded chart & paste to another sheet. |
Sheets(«Sheet1»).ChartObjects(1).Copy Sheets(«Sheet2»).Activate Range(«A1»).Select ActiveSheet.Paste |
||
Delete Method | objChartObject.Delete |
Deletes an embedded chart (ChartObject object) Ex. Sheets(«Sheet1»).ChartObjects(2).Delete |
Select Method | objChartObject.Select(Replace) | Selects the specified ChartObject object (embedded chart) — refer the Select Method of the Chart object where this has been explained in detail. |
Duplicate Method | objChartObject.Duplicate | Duplicates an embedded chart and references the duplicate copy. |
Sub Chart_DuplicateMethod() Dim objChtDupl As Object ‘returns object type: ChartObject ‘using the Duplicate Method to return reference to the duplicate copy of a ChartObject (embedded chart) ‘Duplicate Method is used to obtain a reference to a Shape in a worksheet, corresponding to a ChartObject, whereas using the Copy Method for a ChartObject object creates a copy which is also a ChartObject object ‘returns the same name for the duplicate copy — «Chart 5» ‘change name of the duplicate copy End Sub |
Child Objects for the ChartObject Object: Above we have discussed: the ShapeRange object — use the ShapeRange Property — objChartObject.ShapeRange — to return the ShapeRange object representing a shape range which is a set of shapes on a document; the Chart object — use the Chart Property — objChartObject.Chart — to return a Chart object which refers to a chart contained in the ChartObject object. Some other child objects which are often used with the ChartObject Object include: Interior Object — use the Interior property — objChartObject.Interior — to return the Interior object, to manipulate the chart element’s interior (inside area); Border Object — use the Border Property — objChartObject.Border — to return a Border object, to manipulate a chart element’s border; Range Object — representing a single cell or a range of cells.
Chart object
Commonly used Properties of the Chart Object: |
||
Property | Syntax | Description |
AutoScaling Property | objChart.AutoScaling | To automatically scale a 3-D chart for the size to be closer to its 2-D equivalent, set this property to True. For using this property, it is required to set the the RightAngleAxes property to True. Set or return a Boolean value, using the AutoScaling Property. |
ChartArea Property | objChart.ChartArea | Returns a ChartArea object which refers to the chart area in a chart. The area where chart data is plotted is the Plot Area — the Plot Area is surrounded by the Chart Area. A 2-D chart’s chart area contains: the axes, the chart title, the axis titles & the legend. A 3-D chart’s chart area contains the chart title & the legend, without including the area where the data is plotted within the chart area (ie. the plot area). The ChartArea object is used to format the chart area. |
ChartStyle Property | objChart.ChartStyle | Sets or returns the chart style for the chart, using an integer value from 1 to 48 corresponding to the options available on the Chart Styles group on the Design tab on the Ribbon. |
ChartTitle Property | objChart.ChartTitle | Returns a ChartTitle object which represents the chart title. The chart title is accessed & manipulated through the properties & methods of the ChartTitle object. |
ChartType Property | objChart.ChartType | Return or set the chart type, as per constants / values defined per the XlChartType Enumeration. Note that not all chart types are available for PivotChart reports. |
DataTable Property | objChart.DataTable | Returns a DataTable object representing the chart data table which displays the chart values. The data table is accessed & manipulated through the properties & methods of the DataTable object. Using the Format property of the DataTable object returns a ChartFormat object which contains the line, fill & effect formatting for the data table — some other child objects which are often used include the Border Object & Font Object. The Chart object is the parent of the DataTable object. |
HasDataTable Property | objChart.HasDataTable | This property uses a Boolean value (Read-write). If you wish to display a data table, set this property to True (False will hide the data table). |
Sub Chart_DataTable() ’embedded chart ‘add a data table to an embedded chart ‘use the DataTable property of the Chart object to return a DataTable object ‘include chart legend with the data table — set ShowLegendKey property to True so that the data table contains the legend ‘use the Font property of the DataTable object to return a Font object to manipulate the font ‘data table not to have vertical cell borders ‘use the Border property of the DataTable object to return a Border object to manipulate the border ‘use the Format property of the DataTable object to return a ChartFormat object which contains the line, fill & effect formatting for the data table End With End With End Sub |
||
DepthPercent Property | objChart.DepthPercent | Sets or returns a 3-D chart’s depth as a percentage of its width. You can use a Long value within a range of 20 to 2000 percent. |
DisplayBlanksAs Property | objChart.DisplayBlanksAs | Set or return how you want to plot blank cells on a chart, as per constants defined in the XlDisplayBlanksAs Enumeration: xlNotPlotted (value 1) — Blanks are not plotted; xlZero (value 2) — Blanks are plotted as zero; xlInterpolated (value 3) — values are interpolated into the chart. |
Elevation Property | objChart.Elevation | Sets or returns the chart elevation (for a 3-D chart), in degrees. The chart elevation means the elevation of the 3-D chart view, which is the height at which the chart is viewed. Default elevation of a new chart is 0 degrees — you can tilt the chart up by changing the chart elevation to say, 25 degrees. You can use a value within a range of -90 to 90 degrees, except for 3-D Bar charts wherein the range should be between 0 to 44. For most charts the default value is 15 degrees. |
Floor Property | objChart.Floor | Returns the Floor object, which represents the floor of a 3-D chart. You can thus manipulate the Floor object to set the thickness of the floor (Floor.Thickness Property), use formatting (Floor.Format Property), set the floor color — Floor.Interior.Color = RGB(255, 0, 0) -, and so on. |
HasAxis Property | objChart.HasAxis(Index1, Index2) |
Set (or returns) the axes which will be displayed for a chart. Atleast one argument is required to be specified. The Index1 argument specifies the axis type as defined in the XlAxisType Enumeration: xlCategory (value 1) — Axis displays categories, also referred as the x-axis; xlValue (value 2) — Axis displays values, also referred as y-axis; xlSeriesAxis (value 3) — Axis displays data series for 3-D charts, also referred as the z-axis representing depth of the chart. The Index2 argument specifies the Axis Group as defined in the XlAxisGroup Enumeration: xlPrimary (value 1) — primary axis (default axis); xlSecondary (value 2) — secondary axis. The axis group can either be xlPrimary which is the default, or it can be xlSecondary where the chart has multiple series. 3-D charts cannot have secondary axis. Note that changing the chart type or the AxisGroup property might create or delete axes. To turn on the primary x-axis for a chart: Sheets(«Sheet1»).ChartObjects(1).Chart.HasAxis(xlCategory, xlPrimary) = True |
HasLegend Property | objChart.HasLegend | This property uses a Boolean value — True displays and turns on a legend for the chart (Read-write). The Legend is visible and the Legend object’s properties & methods can be used only if the HasLegend property is True. There can be only one Legend in a chart, and multiple LegendEntry objects can be contained in the Legend object. |
HasTitle Property | objChart.HasTitle | This property uses a Boolean value — True displays a chart title (Read-write). The ChartTitle object exists and can be used only if the HasTitle property returns True. |
HeightPercent Property | objChart.HeightPercent | Sets or returns a 3-D chart’s height as a percentage of its width. You can use a Long value within a range of 5 to 500 percent. |
Legend Property | objChart.Legend | Returns a Legend object, which refers to the chart legend and can be manipulated through its properties & methods. There can be only one Legend in a chart, and multiple LegendEntry objects can be contained in the Legend object. |
Name Property | objChart.Name | Sets or returns the name of a ChartObject object or a Chart object, as a string value. This property is read only for a Chart object (embedded chart), read-write for a ChartObject (embedded chart), and read-write for a Chart object (chart sheet). |
‘Name property is read only for a Chart object (embedded chart): ‘read-write for a ChartObject (embedded chart): ‘Name property is read-write for a Chart object (chart sheet): |
||
Parent Property | objChart.Parent | Returns the parent object of the specified chart object. |
Perspective Property | objChart.Perspective | Sets or returns the perspective for the 3-D chart view. You can use a Long value in the range of 0 to 100 for this property. If the RightAngleAxes property is set to True (ie. if the chart axes are at right angles), the Perspective Property will have no effect. |
PlotArea Property | objChart.PlotArea | Returns a PlotArea object which refers to the plot area of a chart. The area where chart data is plotted is the Plot Area — the Plot Area is surrounded by the Chart Area. A 2-D chart’s plot area contains: the data markers, gridlines, data labels, trendlines & optional chart items placed in the chart area. A 3-D chart’s plot area additionally contains: the walls, floor, axes, axis titles & tick-mark labels in the chart. The PlotArea Object is used to format the plot area. |
PlotBy Property | objChart.PlotBy |
Set or return how to plot data on the chart — to plot data by columns use the constant xlColumns (value 2), and to plot data by rows use the constant xlRows (value 1). Where the source data range is arranged so that data series is in a column (the series name is in the first row and the values appear in below rows within the column), use xlColumns, and if data series is in a row, use xlRows. This property is read-only for PivotChart reports and returns xlColumns always. Ex. MsgBox Sheets(«Sheet1»).ChartObjects(1).Chart.PlotBy — returns 2 for data plotted by columns. |
RightAngleAxes Property | objChart.RightAngleAxes | Set or return the chart axes to be at right angles, for 3-D Line, Column & Bar charts. Use a Boolean value for this property, so that using True will set the axes to intersect at right angles. This property is not dependent on or affected by chart rotation or elevation. Note that if the RightAngleAxes property is set to True, using the Perspective Property will have no effect. |
Rotation Property | objChart.Rotation | Sets or returns the rotation of the 3-D chart view, in degrees. The rotation of the 3-D chart view indicates the rotation of the plot area around the z-axis (the depth axis). You can turn a chart around & around by changing the value of the Rotation property. You can use a value within a range of 0 to 360 degrees, except for 3-D Bar charts wherein the range should be between 0 to 44. For most charts the default value is 20 degrees. Note that rotation value is rounded to the nearest integer. |
Visible Property | objChart.Visible | Sets or return a value (as specified in the XlSheetVisibility Enumeration) which determines whether the chart object (chart sheet) is visible or not viz. xlSheetHidden (value 0) — hides the chart sheet which can be made visible via menu, xlSheetVeryHidden (value 2) — hides the chart sheet which can be made visible only by using this property and not via menu by the user, xlSheetVisible (value -1) — make the chart sheet visible. Ex. Charts(1).Visible = xlSheetVeryHidden — hides thechart sheet, and to make the chart sheet visible use either of the following: Charts(1).Visible = xlSheetVisible or Charts(1).Visible = True. |
Walls Property | objChart.Walls | Returns a Walls Object, which refers to the walls of a 3-D chart (all walls are returned as a unit because there is no object that refers to a single wall). |
BackWall Property | objChart.BackWall | Returns a Walls Object to individually format the back wall of a 3-D chart. |
SideWall Property | objChart.SideWall | Returns a Walls Object to individually format the side wall of a 3-D chart. |
‘set border color for border of all walls to red ‘individually format the side wall — set interior pattern to Checkerboard ‘individually format the back wall — set interior color to blue ‘set floor interior color to red ‘set floor thickness to 12 |
||
Commonly used Methods of the Chart Object: |
||
Method | Syntax | Description |
Activate Method | objChart.Activate |
Use the Activate Method of the Chart object to activate a chart sheet and make it the active chart. Use the Activate Method of the ChartObject object to activate an embedded chart (ChartObject object) and make it the active chart — Syntax: objChartObject.Activate. The ActiveChart property can be used to refer to a chart which is the active object — a chart sheet is active if it has been selected by the user or it has been activated using the Activate method; an embedded chart is active if it has been selected by the user or if the ChartObject object in which it is contained has been activated using the Activate method. Example: activate chart sheet — Charts(1).Activate, activate embedded chart — Sheets(«Sheet1»).ChartObjects(1).Activate, return name of active chart — MsgBox ActiveChart.Name. |
Axes Method | objChart.Axes(Type, AxisGroup) | Returns a single Axis or Axes collection (collection of all Axis objects) in a chart. Both arguments are optional to specify. Specify the axis to be returned in the Type argument — you can use any of the 3 constants for this argument: xlCategory (value 1) — Axis displays categories, also referred as the x-axis; xlValue (value 2) — Axis displays values, also referred as y-axis; xlSeriesAxis (value 3) — Axis displays data series for 3-D charts, also referred as the z-axis representing depth of the chart. Specify the axis group in the AxisGroup argument — xlPrimary (value 1) — primary axis (default axis); xlSecondary (value 2) — secondary axis. The axis group can either be xlPrimary which is the default, or it can be xlSecondary where the chart has multiple series. 3-D charts cannot have secondary axis. |
Copy Method | objChart.Copy(Before, After) |
Copies a chart object (chart sheet only) to another location in the workbook. Use the arguments to specify the sheet before (or after) which to place the copied sheet, and you can specify only one argument at a time ie. either Before or After, and if no argument is specified a new workbook is created wherein the copied sheet is placed. Ex. copy chart sheet named «ChSheet» and place the copy after Sheet1: Charts(«ChSheet»).Copy After:=Sheets(«Sheet1») |
Delete Method | objChart.Delete |
Use the Delete Method of the Chart object to delete a chart sheet. Use the Delete Method of the ChartObject object to delete an embedded chart (ChartObject object) Ex. Charts(«ChSheet»).Delete, or Sheets(«Sheet1»).ChartObjects(2).Delete. |
Select Method | objChart.Select(Replace) | Use the Select Method of the Chart object to select the specified chart object (chart sheet), and use the Select Method of the ChartObject object to select the specified ChartObject object (embedded chart). The Replace argument is optional, where a False value is used to extend the previous selection with the specified chart and include both in the current selection, whereas a True value is used to only include the specified chart in the current selection excluding or replacing the previous selection. |
‘selects the 2 chart objects (chart sheets) ‘selects the 2 chart objects (chart sheets) ‘selects second embedded chart (ChartObject object) only: ‘selects the 2 embedded charts (ChartObject objects): ‘to deselect the active ChartObject: |
||
Location Method | objChart.Location(Where, Name) | Moves the chart to a new location as specified. The Where argument is required to be specified, and it specifies the location where the chart is to be located — use xlLocationAsNewSheet (value 1) to move a chart to a new sheet; use xlLocationAsObject (value 2) to embed a chart in an existing sheet; use xlLocationAutomatic (value 3) to let excel control the location. The Name argument specifies the name of the sheet wherein the chart is to be embedded if the Where argument specifies xlLocationAsObject; and if the Where argument specifies xlLocationAsNewSheet the Name argument specifies the name of the new sheet. The Name argument is necessary to specify only if the Where argument specifies xlLocationAsObject, otherwise it is Optional. |
‘moves the embedded chart (the first ChartObject in «Sheet1») to a new chart sheet created with the name «RevenuesChSheet» Sheets(«Sheet1″).ChartObjects(1).Chart.Location Where:=xlLocationAsNewSheet, Name:=»RevenuesChSheet« |
||
Move Method | objChart.Move(Before, After) |
Moves the chart (chart sheet) to another location in the workbook. Both the arguments are optional, and only one can be used at a time. Before & After arguments refer to the sheet before or after which the chart is to be placed — if both these arguments are omitted, a new workbook is created containing the moved chart. Example: move the chart sheet (named «RevenuesChSheet») to a new location and places it after the last sheet in the workbook: Charts(«RevenuesChSheet»).Move After:=Sheets(Sheets.count) |
PrintPreview Method | objChart.PrintPreview(EnableChanges) |
Displays a print preview of the chart object. The EnableChanges argument (uses a Boolean value) is optional, and setting to True value will enable the user to change the margins & page setup options in print preview. Ex: Sheets(«Sheet1»).ChartObjects(2).Chart.PrintPreview EnableChanges:=True |
PrintOut Method | objChart.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName, IgnorePrintAreas) |
Prints the chart. All arguments are optional. The From & To arguments specify the starting page no & ending page no respectively, and omitting these will start printing from the first page & end at the last page (Note that page reference is to printed pages & not in re. of pages in the sheet or workbook). Not specifying the Copies argument will print one copy by default. Set Preview argument to True to display a print preview for the chart, where False is the default value which will print the chart immdeiately. Specify the printer name using the ActivePrinter argument. Set the PrintToFile argument to True to print to a file, instead of printing to a printer, and in this case it is required to specify a file name using the PrToFileName argument. To collate multiple copies, set the Collate argument to True — this will print multiple copies for collation instead of printing all copies of one page, then all copies of the next page, and so on. Setting the argument IgnorePrintAreas to True will print the entire chart object not taking into account the print area, whereas if set to False it will print only the specified print area. Ex: Sheets(«Sheet1″).ChartObjects(2).Chart.PrintOut , , Copies:=2, Preview:=False, ActivePrinter:=»HP LaserJet 1022 on Ne02:» |
‘Print Preview all embedded charts in a sheet |
||
‘Print all embedded charts in a sheet |
||
‘Printing a chart sheet — page setup & printout: ‘use the PageSetup object to manipulate page setup attributes viz. margin, paper size, header, footer, etc ‘using ChartSize is only applicable to chart sheets (not valide for embedded charts) — xlScreenSize prints the chart the same size as it appears on the screen End With ‘print out 1 copy of the chart sheet |
||
SeriesCollection Method | objChart.SeriesCollection(Index) | Returns either a single Series object or the SeriesCollection object. The Series object refers to a single series in a chart, and is a member of the SeriesCollection object. A SeriesCollection object refers to a collection of all the Series objects in a chart. The Index argument specifies the number or name of the series — index number represents the order in which the series were added, with the first series added to the chart being index number 1 ie. objChart.SeriesCollection(1), and the last added series index number being objChart.SeriesCollection(SeriesCollection.Count). |
ChartGroups Method | objChart.ChartGroups(Index) | Returns either a ChartGroup object (single chart group) or a ChartGroups object. The ChartGroup object refers to one or more series plotted in a chart with the same format, and is a member of the ChartGroups object. A ChartGroups object refers to a collection of all the chart groups objects in a chart. The Index argument specifies the chart group index number. Heirarchy: Chart > one or more chart groups in a chart (ex. a line chart group and a bar chart group …) > one or more Series objects in a chart group > one or more Points objects in a series. |
SetSourceData Method | objChart.SetSourceData(Source, PlotBy) | The Source argument is necessary to specify and refers to the range containing the source data for the chart. The PlotBy argument (optional) specifies how to plot data on the chart — to plot data by columns use the constant xlColumns (value 2), and to plot data by rows use the constant xlRows (value 1). |
SetElement Method | objChart.SetElement(Element) |
Specifies chart elements to set on a chart. It is necessary to specify the Element argument which specifies the type of chart element as per the MsoChartElementType enumeration constants. This method covers commands in the Layout tab of Chart Tools: complete Labels group / Axes group / Analysis group and the PlotArea / Chart Wall / Chart Floor buttons in the Background group. MsoChartElementType Enumeration specifies if the chart elements are to be displayed and how to display them viz. msoElementChartTitleNone (value 0) — Do not display chart title; msoElementChartTitleAboveChart (value 2) — Display title above chart; msoElementDataLabelNone (value 200) — Do not display data label; msoElementDataLabelLeft (value 206) — Display data label to the left; msoElementLegendNone (value 100) — Do not display legend; msoElementLegendRight (value 101) — Display legend at the right; msoElementPlotAreaNone (value 1000) — Do not display plot area; msoElementPlotAreaShow (value 1001) — Display plot area; msoElementPrimaryCategoryAxisNone (value 348) — Do not display primary category axis; msoElementPrimaryCategoryAxisTitleBelowAxis (value 302) — Display primary category axis title below the axis; msoElementPrimaryValueGridLinesNone (value 328) — Do not display grid lines along primary value axis; msoElementPrimaryValueGridLinesMajor (value 330) — Display major gridlines along primary value axis; and so on. |
ApplyDataLabels Method | objChart.ApplyDataLabels(Type, LegendKey, AutoText, HasLeaderLines, ShowSeriesName, ShowCategoryName, ShowValue, ShowPercentage, ShowBubbleSize, Separator) |
Use this method to apply data labels to all the chart series. All arguments are optional to specify. The Type argument specifies the type of data label applied to a chart: xlDataLabelsShowValue (value 2 — Default) — value for the point; xlDataLabelsShowPercent (value 3) — percentage of the total, & is available only for pie charts & doughnut charts; xlDataLabelsShowLabel (value 4) — category for the point; xlDataLabelsShowLabelAndPercent (value 5) — category for the point & percentage of the total, & is available only for pie charts & doughnut charts; xlDataLabelsShowBubbleSizes (value 6) — show bubble size in reference to the absolute value; xlDataLabelsShowNone (value -4142) — no data labels displayed. Set the LegendKey argument to True to display legend key next to the data points, where False is the default value. Set the AutoText argument to True to automatically generate appropriate text based on content. Set the HasLeaderLines argument to True to display leader lines for the series. For the arguments of ShowSeriesName / ShowCategoryName / ShowValue / ShowPercentage / ShowBubbleSize, pass a boolean value to enable (ie. display) or disable the series name / category names / data values / percentages / bubble size, for the data label. The Separator argument specifies the separator for the data label. |
Apply Data Lables, & display Category Names, Values & Percentages separated by «/» (forward slash) & also display Legend Keys: |
||
ChartWizard Method | objChart.ChartWizard(Source, Gallery, Format, PlotBy, CategoryLabels, SeriesLabels, HasLegend, Title, CategoryTitle, ValueTitle, ExtraTitle) |
Use this method to quickly format a chart & modify specific properties. This method allows you to make modifications in a chart without setting each property separately and by changing only the specified properties. All arguments are optional — however the Source argument is necessary to specify unless the Selection is an embedded chart on the active worksheet or the active sheet is an existing chart, else the method fails. Source argument specifies source data range for a new chart, and if omitted, the selected embedded chart on the active worksheet or the active chart sheet is considered. The Gallery argument specifies the chart type as per constants defined in XlChartType Enumeration (viz. xlLineMarkers, xlColumnClustered, xlPie, …) . The Format argument specifies an option number (1 to 10) depending on the chart type, and if omitted, a default value is chosen based on data source & chart type. The PlotBy argument specifies how to plot data for series on the chart — to plot data by columns use the constant xlColumns (value 2), and to plot data by rows use the constant xlRows (value 1). The CategoryLabels argument specifies the number of category labels contained in the source range rows or columns, as an integer value, with a minimum of 0 (zero) where the source range does not contain category labels. The SeriesLabels argument specifies the number of series labels contained in the source range rows or columns, as an integer value, with a minimum of 0 (zero) where the source range does not contain series labels. Specify True for the HasLegend argument for the chart to have a legend. Specify text for the chart title / category axis title / value axis title, using the Title / CategoryTitle / ValueTitle arguments respectively. The ExtraTitle argument specifies the secondary value axis title (2-D chart) or the series axis title (3-D charts). |
Example: create a chart & use the ChartWizard Method of the Chart object — refer Image 3
Sub ChartWizard_1() ‘create a chart & use the ChartWizard Method of the Chart object — refer Image 3 Dim rngSourceData As Range, wsData As Worksheet, wsChart As Worksheet ‘declare a ChartObject Dim oChObj As ChartObject Set wsData = Sheets(«Sheet1») ‘set sheet for embedded chart Set wsChart = Sheets(«Sheet1») ‘set source data range Set rngSourceData = wsData.Range(«A1:D5») ‘the Add method (of the ChartObjects object) is used to create a new empty embedded chart and add it to the collection (ChartObjects object) in the specified sheet Set oChObj = wsChart.ChartObjects.Add(Left:=wsChart.Columns(«A»).Left, Width:=320, Top:=wsChart.Rows(6).Top, Height:=200) With oChObj.Chart ‘chart type ‘Line with Markers’; 2 category labels (in 2 columns — A & B); 1 series labels (row 1); .ChartWizard Source:=rngSourceData, Gallery:=xlLineMarkers, Format:=1, PlotBy:=xlColumns, CategoryLabels:=2, SeriesLabels:=1, HasLegend:=True, title:=»Sales-Profit», CategoryTitle:=»Qtr — Yr», ValueTitle:=»$ in thousands» ‘set distance between the levels of labels, and the distance between the first level and the axis line .Axes(xlCategory).TickLabels.Offset = 0 End With |
Child objects (of the Chart object) which are often used with charts: ChartArea Object; ChartGroup Object; ChartTitle Object; Corners Object; DataTable Object; Floor Object; Hyperlinks Object; Legend Object; PageSetup Object; PivotLayout Object; PlotArea Object; Shapes Object; Tab Object; Walls Object. Many of these are discussed in detail below.
Example: Add an embedded chart, use properties & methods of the ChartObject object & Chart object — refer image 4a & 4b
Sub Chart_Properties_Methods()
‘Add an embedded chart, use properties & methods of the ChartObject object & Chart object — refer image 4a & 4b
Dim rngSourceData As Range, wsData As Worksheet, wsChart As Worksheet
Set wsData = Sheets(«Sheet1»)
Set wsChart = Sheets(«Sheet2»)
Set rngSourceData = Union(wsData.Range(«B24:B28»), wsData.Range(«D24:D28»))
‘declare a ChartObject
Dim oChObj As ChartObject
‘the Add method (of the ChartObjects object) is used to create a new empty embedded chart and add it to the collection (ChartObjects object) in the specified sheet
Set oChObj = wsChart.ChartObjects.Add(Left:=2, Width:=350, Top:=5, Height:=200)
‘using the Chart Property of the ChartObject object returns a Chart object which refers to a chart
With oChObj.Chart
‘use ChartType Property of the Chart object to set type of chart — Line with Markers
.ChartType = xlLineMarkers
‘use SetSourceData Method of the Chart object to set the range of source data for the chart
.SetSourceData Source:=rngSourceData, PlotBy:=xlColumns
‘the Parent property of the Chart object returns its Parent object ie. ChartObject object (oChObj)
With .Parent
‘set the embedded chart to be free-floating so that it does not move or size with its underlying cells
.Placement = xlFreeFloating
‘align the left edge of the embedded chart with the left edge of the worksheet’s column B
.Left = wsChart.Columns(«B«).Left
‘set rounded corners for the embedded chart
.RoundedCorners = True
‘using the Name Property of the ChartObject object — set the name of the embedded chart to «AnnualSalesProfit»
.Name = «AnnualSalesProfit«
End With
‘using the Chart.SeriesCollection Method to return a single series (Series object) by its Index number — set the axis group for the specified series using the AxisGroup Property of the Series object
‘use the XlAxisGroup Enumeration constants to specfy the type of axis group as xlPrimary (Primary axis group)
.SeriesCollection(1).AxisGroup = xlPrimary
.SeriesCollection(2).AxisGroup = xlPrimary
‘using the XValues property of the Series object, set an array of X values (ie. Category Labels), for series 1
.SeriesCollection(1).XValues = wsData.Range(«A25:A28»)
‘use the NewSeries Method of the SeriesCollection object to create a new series
With .SeriesCollection.NewSeries
.AxisGroup = xlSecondary
‘name the new series
.Name = wsData.Range(«C24»)
‘using the Values property of the Series object, set Y values for new series
.Values = wsData.Range(«C25:C28»)
End With
‘using constants specified in the MsoChartElementType Enumeration, display the axis title & determine how to display it (setting the HasTitle property to True is not required here)
‘Place primary value axis title below the axis
.SetElement msoElementPrimaryValueAxisTitleBelowAxis
‘use the Caption Property of the ChartTitle object to set the text for the chart title
.Axes(xlValue, xlPrimary).AxisTitle.Caption = «Sales & Costs«
.SetElement msoElementSecondaryValueAxisTitleBelowAxis
.Axes(xlValue, xlSecondary).AxisTitle.Caption = «Profits«
‘refer the Axis object — Value axis in the Secondary axis group — Axis object is a member of the Axes collection
With .Axes(xlValue, xlSecondary)
‘set the minimum and maximum values for the value axis
.MaximumScale = WorksheetFunction.RoundUp(WorksheetFunction.Max(wsData.Range(«C25:C28»)) * 1.55, -4)
.MinimumScale = WorksheetFunction.RoundDown(WorksheetFunction.Min(wsData.Range(«C25:C28»)) * 0.85, -4)
.MajorUnit = 20000
End With
‘using constant values in MsoChartElementType Enumeration to specify if the chart elements are to be displayed and how to display them
‘Display chart title above chart
.SetElement msoElementChartTitleAboveChart
‘Display major gridlines along primary value axis
.SetElement msoElementPrimaryValueGridLinesMajor
‘turn off legend
.SetElement msoElementLegendNone
‘Display data table with legend keys
.SetElement msoElementDataTableWithLegendKeys
End With
End Sub
Below is an example for creating an embedded chart, of type line with markers, and manipulating various chart elements — it is divided into 8 parts / subs, for clear step by step explanations. Sub 1: add an embedded chart; Sub 2: manipulate Chart Title; Sub 3: manipulate Chart Area; Sub 4: manipulate Chart Axis & Axis Title; Sub 5: manipulate Chart Series; Sub 6: manipulate Plot Area; Sub 7: align chart elements; Sub 8: manipulate Chart Legend.
Example: Part 1 of 8 — Add an embedded chart — refer Image 1.1
Sub EmbChart_ChartObject_1()
‘Add an embedded chart — refer Image 1.1
Dim rngSourceData As Range, wsData As Worksheet, wsChart As Worksheet
Set wsData = Sheets(«Sheet18»)
Set wsChart = Sheets(«Sheet19»)
Set rngSourceData = wsData.Range(«C1:D9»)
‘declare a ChartObject
Dim oChObj As ChartObject
‘delete existing embedded charts in the worksheet
For Each oChObj In wsChart.ChartObjects
oChObj.Delete
Next
‘the Add method (of the ChartObjects object) is used to create a new empty embedded chart and add it to the collection (ChartObjects object) in the specified sheet — left edge align to the left edge of column B, top edge align to the top of row 2
Set oChObj = wsChart.ChartObjects.Add(Left:=wsChart.Columns(«B«).Left, Width:=450, Top:=wsChart.Rows(2).Top, Height:=255)
‘using the Chart Property of the ChartObject object returns a Chart object which refers to a chart (contained in the ChartObject object)
With oChObj.Chart
‘use ChartType Property of the Chart object to set type of chart — Line with Markers
.ChartType = xlLineMarkers
‘use SetSourceData Method of the Chart object to set the range of source data for the chart
.SetSourceData Source:=rngSourceData, PlotBy:=xlColumns
‘the ChartTitle object exists and can be used only if the HasTitle property (of the Chart object) is True
.HasTitle = True
‘using the Chart.SeriesCollection Method to return a single series (Series object) by its name or Index number
‘the AxisGroup Property of the Series object sets the axis group for series — using the XlAxisGroup Enumeration to specfy the type of axis group as xlPrimary (Primary axis group)
.SeriesCollection(wsData.Range(«C1»).Value).AxisGroup = xlPrimary
‘specfy the type of axis group as xlSecondary (Secondary axis group) for series
.SeriesCollection(wsData.Range(«D1»).Value).AxisGroup = xlSecondary
‘refer ChartObject object (oChObj)
With .Parent
‘set the embedded chart to be free-floating so that it does not move or size with its underlying cells
.Placement = xlFreeFloating
‘set rounded corners for the embedded chart
.RoundedCorners = True
‘Change the name of the embedded chart to «QtrlySalesProfitChart» using the Name Property
.Name = «QtrlySalesProfitChart«
End With
End With
End Sub
Содержание
- 1 Activates the ChartObject named Chart 1
- 2 Add Chart
- 3 Adding a Chart Sheet Using VBA Code
- 4 Adding a New Series to the chart identified by the object variable myChart, drawing the data from the range C4:K4 on the active worksheet in the active workbook, using rows:
- 5 add the data labels using the following code:
- 6 Automatically generating a chart without user interaction
- 7 convert an existing chart to use arrays instead of cell references and make it independent of the original data
- 8 Creating a Chart
- 9 Creating a Chart on an Existing Worksheet
- 10 Creating a Chart Using the Chart Object
- 11 Creating an Embedded Chart
- 12 Creating a New Chart Using the ChartWizard Method
- 13 Creating a New Series, use the NewSeries method with the SeriesCollection collection.
- 14 Creating Charts
- 15 Determining a chart»s source data
- 16 Extending an Existing Series in the chart identified by the object variable myChart using the data in the cells P3:P8 on the worksheet named Chart Data:
- 17 Get Chart SeriesCollection value
- 18 Get Chart sheet
- 19 Get Embedded Charts
- 20 In most cases you can avoid using the worksheet Index property
- 21 Insert chart sheets after each worksheet
- 22 Inserts a chart before each sheet
- 23 Inserts a chart before each sheet 2
- 24 Insert two chart sheets after the last worksheet in the active workbook. The chart sheets receive default names, such as Chart1 and Chart2:
- 25 Modifying the chart type
- 26 Producing an Excel worksheet on a Word ocument
- 27 Reference Char object from ActiveSheet
- 28 Referencing Charts and Chart Objects in VBA Code
- 29 Retrieving data point labels from field names in the worksheet
- 30 Select a chart object
- 31 Show chart
- 32 Specify Exact Location
- 33 Specifying the Chart Type
- 34 Specifying the Source Data for the Chart by using the SetSourceData method of the Chart object
- 35 To ensure that a chart is selected, you can add a statement to determine if a chart is active.
- 36 Use For Each to loop through all chart objects
Activates the ChartObject named Chart 1
<source lang="vb">
Sub activate()
ActiveSheet.ChartObjects("Chart 1").Activate
End Sub
</source>
Add Chart
<source lang="vb">
Sub AddChart()
Dim aChart As Chart ActiveSheet.ChartObjects.Delete Set aChart = Charts.Add Set aChart = aChart.Location(Where:=xlLocationAsObject, Name:="Sheet1") With aChart .ChartType = xlColumnClustered .SetSourceData Source:=Sheets("Sheet1").Range("A3:D7"), _ PlotBy:=xlRows .HasTitle = True .ChartTitle.Text = "=Sheet1!R3C1" With .Parent .Top = Range("F3").Top .Left = Range("F3").Left .Name = "MangoesChart" End With End With
End Sub
</source>
Adding a Chart Sheet Using VBA Code
<source lang="vb"> Sub AddChartSheet() Dim myChart As Chart Set myChart = Charts.add With myChart .SetSourceData Source:=Sheets("Sheet1").range("A3:D7"), _ PlotBy:=xlRows .ChartType = xlColumnClustered .HasTitle = True .ChartTitle.text = "Mangoes" End With End Sub </source>
Adding a New Series to the chart identified by the object variable myChart, drawing the data from the range C4:K4 on the active worksheet in the active workbook, using rows:
<source lang="vb">
Sub series()
Dim myChartObject As ChartObject Set myChartObject = ActiveSheet.ChartObjects.Add(Left:=200, Top:=200, _ Width:=400, Height:=300) myChartObject.Chart.SetSourceData Source:= _ ActiveWorkbook.Sheets("Chart Data").Range("A1:E5") myChartObject.SeriesCollection.Add Source:=ActiveSheet.Range("C4:K4"), Rowcol:=xlRows
End Sub
</source>
add the data labels using the following code:
<source lang="vb"> Sub AddDataLabels() Dim seSales As Series Dim pts As Points Dim pt As Point Dim rngLabels As range Dim iPointIndex As Integer Set rngLabels = range("B4:G4") Set seSales = ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1) seSales.HasDataLabels = True Set pts = seSales.Points For Each pt In pts iPointIndex = iPointIndex + 1 pt.DataLabel.text = rngLabels.cells(iPointIndex).text pt.DataLabel.font.bold = True pt.DataLabel.Position = xlLabelPositionAbove Next pt End Sub </source>
Automatically generating a chart without user interaction
<source lang="vb">
Sub CreateChart(r)
Dim TempChart As Chart Application.ScreenUpdating = False Set CatTitles = ActiveSheet.range("A2:F2") Set SrcRange = ActiveSheet.range(Cells(r, 1), Cells(r, 6)) Set SourceData = Union(CatTitles, SrcRange) Set TempChart = Charts.Add With TempChart .ChartType = xlColumnClustered .SetSourceData Source:=SourceData, PlotBy:=xlRows .HasLegend = False .ApplyDataLabels Type:=xlDataLabelsShowValue, _ LegendKey:=False .ChartTitle.Font.Size = 14 .ChartTitle.Font.Bold = True .Axes(xlValue).MaximumScale = 0.6 .Axes(xlCategory).TickLabels.Font.Size = 10 .Axes(xlCategory).TickLabels.Orientation = _ xlHorizontal .Location Where:=xlLocationAsObject, name:="Sheet1" End With With ActiveSheet.ChartObjects(1) .Width = 300 .Height = 150 .Visible = False End With
End Sub
</source>
convert an existing chart to use arrays instead of cell references and make it independent of the original data
<source lang="vb"> Sub ConvertSeriesValuesToArrays() Dim seSeries As Series Dim myChart As Chart On Error GoTo Failure Set myChart = ActiveSheet.ChartObjects(1).Chart For Each seSeries In myChart.SeriesCollection seSeries.Values = seSeries.Values seSeries.XValues = seSeries.XValues seSeries.name = seSeries.name Next seSeries Exit Sub
Failure:
MsgBox "Sorry, the data exceeds the array limits""" End Sub </source>
Creating a Chart
<source lang="vb">
Sub chart()
Dim myChartSheet As Chart Set myChartSheet = ActiveWorkbook.Sheets.Add _ (After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count), _ Type:=xlChart)
End Sub
</source>
Creating a Chart on an Existing Worksheet
<source lang="vb">
Sub charObj()
Dim myChartObject As ChartObject Set myChartObject = ActiveSheet.ChartObjects.Add(Left:=200, Top:=200, _ Width:=400, Height:=300)
End Sub
</source>
Creating a Chart Using the Chart Object
<source lang="vb">
Sub CreateExampleChartVersionII()
Dim ws As Worksheet Dim rgChartData As Range Dim myChart As Chart Set ws = ThisWorkbook.Worksheets("Basic Chart") Set rgChartData = ws.Range("B1").CurrentRegion Set myChart = Charts.Add Set myChart = myChart.Location(xlLocationAsObject, ws.Name) With myChart .SetSourceData rgChartData, xlColumns .HasTitle = True .ChartTitle.Caption = "Version II" .ChartType = xlColumnClustered With .Axes(xlCategory) .HasTitle = True .AxisTitle.Caption = "Year" End With With .Axes(xlValue) .HasTitle = True .AxisTitle.Caption = "GDP in billions of $" End With End With Set myChart = Nothing Set rgChartData = Nothing Set ws = Nothing
End Sub
</source>
Creating an Embedded Chart
<source lang="vb">
Public Sub AddEmbeddedChart()
Dim dataRange As Range Set dataRange = ActiveWindow.Selection "Chart selected data ActiveSheet.ChartObjects.Add Left:=200, Top:=50, Width:=500,Height:=350 ActiveSheet.ChartObjects(1).Activate With ActiveChart "Set chart properties .ChartType = xlColumnClustered .SeriesCollection.NewSeries .HasLegend = True .Legend.Position = xlRight .Axes(xlCategory).MinorTickMark = xlOutside .Axes(xlValue).MinorTickMark = xlOutside .Axes(xlValue).MaximumScale = Application.WorksheetFunction.RoundUp(Application.WorksheetFunction.Max(dataRange), -1) .Axes(xlCategory, xlPrimary).HasTitle = True .Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text ="X-axis Labels" .Axes(xlValue, xlPrimary).HasTitle = True .Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Y-axis" .SeriesCollection(1).name = "Sample Data" .SeriesCollection(1).Values = dataRange End With
End Sub
</source>
Creating a New Chart Using the ChartWizard Method
<source lang="vb">
Sub CreateExampleChartVersionI()
Dim ws As Worksheet Dim rgChartData As Range Dim myChart As Chart Set ws = ThisWorkbook.Worksheets("Sheet1") Set rgChartData = ws.Range("B1").CurrentRegion Set myChart = Charts.Add Set myChart = myChart.Location(xlLocationAsObject, ws.Name) With myChart .ChartWizard _ Source:=rgChartData, _ Gallery:=xlColumn, _ Format:=1, _ PlotBy:=xlColumns, _ CategoryLabels:=1, _ SeriesLabels:=1, _ HasLegend:=True, _ Title:="Version I", _ CategoryTitle:="Year", _ ValueTitle:="GDP in billions of $" End With Set myChart = Nothing Set rgChartData = Nothing Set ws = Nothing
End Sub
</source>
Creating a New Series, use the NewSeries method with the SeriesCollection collection.
<source lang="vb">
Sub newSeries()
Dim myChartObject As ChartObject Set myChartObject = ActiveSheet.ChartObjects.Add(Left:=200, Top:=200, _ Width:=400, Height:=300) myChartObject.Chart.SetSourceData Source:= _ ActiveWorkbook.Sheets("Chart Data").Range("A1:E5") myChartObject.SeriesCollection.Add Source:=ActiveSheet.Range("C4:K4"), Rowcol:=xlRows myChartObject.SeriesCollection.NewSeries
End Sub
</source>
Creating Charts
<source lang="vb">
Common Excel Chart Types
Chart VBA Constant (ChartType property of Chart object)
Column xlColumnClustered, xlColumnStacked, xlColumnStacked100
Bar xlBarClustered, xlBarStacked, xlBarStacked100
Line xlLine, xlLineMarkersStacked, xlLineStacked
Pie xlPie, xlPieOfPie
Scatter xlXYScatter, xlXYScatterLines
Public Sub AddChartSheet()
Dim dataRange As Range Set dataRange = ActiveWindow.Selection Charts.Add "Create a chart sheet With ActiveChart "Set chart properties .ChartType = xlColumnClustered .HasLegend = True
» .Legend.Position = xlRight
.Axes(xlCategory).MinorTickMark = xlOutside .Axes(xlValue).MinorTickMark = xlOutside .Axes(xlValue).MaximumScale = _ Application.WorksheetFunction.RoundUp( _ Application.WorksheetFunction.Max(dataRange), -1) .Axes(xlCategory).HasTitle = True .Axes(xlCategory).AxisTitle.Characters.Text = "X-axis Labels" .Axes(xlValue).HasTitle = True .Axes(xlValue).AxisTitle.Characters.Text = "Y-axis" .SeriesCollection(1).name = "Sample Data" .SeriesCollection(1).Values = dataRange End With
End Sub
</source>
Determining a chart»s source data
<source lang="vb">
Sub Test1()
Dim DataRange As range Set DataRange = ActiveSheet.range("A1:A2") ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).Values = DataRange
End Sub
</source>
Extending an Existing Series in the chart identified by the object variable myChart using the data in the cells P3:P8 on the worksheet named Chart Data:
<source lang="vb">
Sub chartSource()
Dim myChartObject As ChartObject Set myChartObject = ActiveSheet.ChartObjects.Add(Left:=200, Top:=200, _ Width:=400, Height:=300) myChartObject.Chart.SetSourceData Source:= _ ActiveWorkbook.Sheets("Chart Data").Range("A1:E5") myChartObject.SeriesCollection.Add Source:=ActiveSheet.Range("C4:K4"), Rowcol:=xlRows myChartObject.SeriesCollection.Extend Source:=Worksheets("Chart Data").Range("P3:P8")
End Sub
</source>
Get Chart SeriesCollection value
<source lang="vb">
Sub Test2()
Dim DataRange As range Set DataRange = Sheets("Sheet1").ChartObjects(1).Chart.SeriesCollection(1).Values
End Sub
</source>
Get Chart sheet
<source lang="vb">
Public Sub GetChartSheets()
Dim myCharts As Sheets Dim chSheet As Chart Set myCharts = ActiveWorkbook.Charts For Each chSheet In myCharts Debug.Print chSheet.name Next
End Sub
</source>
Get Embedded Charts
<source lang="vb">
Public Sub GetEmbeddedCharts()
Dim myChart As ChartObject Dim myCharts As ChartObjects Set myCharts = ActiveSheet.ChartObjects For Each myChart In myCharts Debug.Print myChart.Chart.name Next
End Sub
</source>
In most cases you can avoid using the worksheet Index property
<source lang="vb"> Sub InsertChartsBeforeWorksheets2() Dim myWorksheet As Worksheet For Each myWorksheet In Worksheets Charts.add Before:=myWorksheet Next myWorksheet End Sub </source>
Insert chart sheets after each worksheet
<source lang="vb"> Sub InsertChartsAfterWorksheets() Dim myWorksheet As Worksheet Dim myChart As Chart For Each myWorksheet In Worksheets Set myChart = Charts.add myChart.Move After:=myWorksheet Next myWorksheet End Sub </source>
Inserts a chart before each sheet
<source lang="vb">
Sub InsertChartsBeforeWorksheets()
Dim myWorksheet As Worksheet For Each myWorksheet In Worksheets Charts.Add Before:=Sheets(myWorksheet.Index) Next myWorksheet
End Sub
</source>
Inserts a chart before each sheet 2
<source lang="vb">
Sub InsertChartsBeforeWorksheets2()
Dim myWorksheet As Worksheet For Each myWorksheet In Worksheets Charts.Add Before:=myWorksheet Next myWorksheet
End Sub
</source>
Insert two chart sheets after the last worksheet in the active workbook. The chart sheets receive default names, such as Chart1 and Chart2:
<source lang="vb">
Sub addAfter()
ActiveWorkbook.Sheets.Add After:=Sheets(Sheets.Count), Count:=2, Type:=xlChart
End Sub
</source>
Modifying the chart type
<source lang="vb">
Sub ModifyChart1()
ActiveSheet.ChartObjects("Chart 1").activate ActiveChart.Type = xlArea
End Sub
</source>
Producing an Excel worksheet on a Word ocument
<source lang="vb">
Sub MakeExcelChart()
Dim XLSheet As Object Documents.Add Wbook = "projections.xls" Set XLSheet = GetObject(Wbook, "Excel.Sheet").ActiveSheet XLSheet.range("Value") = 1 XLSheet.range("Change") = 2 XLSheet.Calculate Selection.Font.Size = 14 Selection.Font.Bold = True Selection.TypeText "Monthly Increment: " & Format(2, "0.0%") Selection.TypeParagraph Selection.TypeParagraph XLSheet.range("data").Copy Selection.Paste XLSheet.ChartObjects(1).Copy Selection.PasteSpecial _ Link:=False, _ DataType:=wdPasteMetafilePicture, _ Placement:=wdInLine, DisplayAsIcon:=False Set XLSheet = Nothing
End Sub
</source>
Reference Char object from ActiveSheet
<source lang="vb">
Sub m()
ActiveSheet.ChartObjects(1).Select
End Sub
</source>
Referencing Charts and Chart Objects in VBA Code
<source lang="vb">
Sub SpecifyLocation()
Dim WS As Worksheet Set WS = Worksheets("Sheet1") WS.Shapes.AddChart(xlColumnClustered, Left:=100, Top:=150, Width:=400, Height:=300).Select ActiveChart.SetSourceData Source:=WS.range("A1:E4")
End Sub
</source>
Retrieving data point labels from field names in the worksheet
<source lang="vb">
Sub DataLabelsFromRange()
Dim DLRange As range Dim myChart As Chart Dim i As Integer Set myChart = ActiveSheet.ChartObjects(1).Chart On Error Resume Next Set DLRange = Application.InputBox _ (prompt:="Range for data labels?", Type:=8) If DLRange Is Nothing Then Exit Sub On Error GoTo 0 myChart.SeriesCollection(1).ApplyDataLabels Type:=xlDataLabelsShowValue, AutoText:=True, LegendKey:=False Pts = myChart.SeriesCollection(1).Points.Count For i = 1 To Pts myChart.SeriesCollection(1). _ Points(i).DataLabel.Characters.Text = DLRange(i) Next i
End Sub
</source>
Select a chart object
<source lang="vb">
Sub m()
ActiveWorkbook.Charts(1).Select
End Sub
</source>
Show chart
<source lang="vb">
Sub ShowChart()
UserRow = ActiveCell.Row If UserRow < 2 Or IsEmpty(Cells(UserRow, 1)) Then MsgBox "Move the cell cursor to a row that contains data." Exit Sub End If CreateChart (UserRow)
End Sub
</source>
Specify Exact Location
<source lang="vb">
Sub SpecifyExactLocation()
Dim WS As Worksheet Set WS = Worksheets("Sheet1") WS.Shapes.AddChart(xlColumnClustered, _ Left:=WS.range("C11").Left, _ Top:=WS.range("C11").Top, _ Width:=WS.range("C11:J11").Width, _ Height:=WS.range("C11:C30").Height).Select ActiveChart.SetSourceData Source:=WS.range("A1:E4")
End Sub
</source>
Specifying the Chart Type
<source lang="vb">
Sub chartType()
Dim myChartObject As ChartObject Set myChartObject = ActiveSheet.ChartObjects.Add(Left:=200, Top:=200, _ Width:=400, Height:=300) myChartObject.Chart.SetSourceData Source:= _ ActiveWorkbook.Sheets("Chart Data").Range("A1:E5") myChartObject.ChartType = xlColumnStacked
End Sub
</source>
Specifying the Source Data for the Chart by using the SetSourceData method of the Chart object
<source lang="vb">
Sub width()
Dim myChartObject As ChartObject Set myChartObject = ActiveSheet.ChartObjects.Add(Left:=200, Top:=200, _ Width:=400, Height:=300) myChartObject.Chart.SetSourceData Source:= _ ActiveWorkbook.Sheets("Chart Data").Range("A1:E5")
End Sub
</source>
To ensure that a chart is selected, you can add a statement to determine if a chart is active.
<source lang="vb">
Sub ChartMods2()
If ActiveChart Is Nothing Then MsgBox "Activate a chart." Exit Sub End If ActiveChart.Type = xlArea ActiveChart.ChartArea.font.name = "Calibri" ActiveChart.ChartArea.font.FontStyle = "Regular" ActiveChart.ChartArea.font.Size = 9 ActiveChart.PlotArea.Interior.ColorIndex = xlNone ActiveChart.Axes(xlValue).TickLabels.font.bold = True ActiveChart.Axes(xlCategory).TickLabels.font.bold = True ActiveChart.Legend.Position = xlBottom
End Sub
</source>
Use For Each to loop through all chart objects
<source lang="vb">
Sub ChangeCharts()
Dim myChart As ChartObject For Each myChart In Sheets("Sheet1").ChartObjects myChart.Chart.ChartType = xlLine Next myChart
End Sub
</source>