Excel vba chart setsourcedata

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Chart.SetSourceData method (Excel)

vbaxl10.chm149162

vbaxl10.chm149162

excel

Excel.Chart.SetSourceData

fc41cc05-087a-f53c-2f54-fd6307de51d6

04/16/2019

medium

Chart.SetSourceData method (Excel)

Sets the source data range for the chart.

Syntax

expression.SetSourceData (Source, PlotBy)

expression A variable that represents a Chart object.

Parameters

Name Required/Optional Data type Description
Source Required Range The range that contains the source data.
PlotBy Optional Variant Specifies the way the data is to be plotted. Can be either of the following XlRowCol constants: xlColumns or xlRows.

Example

This example sets the source data range for chart one.

Charts(1).SetSourceData Source:=Sheets(1).Range("a1:a10"), _ 
 PlotBy:=xlColumns

[!includeSupport and feedback]

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 MethodSyntax: 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 ChartObjectSyntax: 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()
‘working with a Shape Range (ie. ShapeRange Object which is a set of shapes)

‘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()
‘return reference to duplicate copy of a ChartObject (embedded chart)

Dim objChtDupl As Object

‘returns object type: ChartObject
MsgBox TypeName(Sheets(«Sheet1»).ChartObjects(«Chart 5»))

‘using the Duplicate Method to return reference to the duplicate copy of a ChartObject (embedded chart)
Set objChtDupl = Sheets(«Sheet1»).ChartObjects(«Chart 5»).Duplicate

‘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 object type: Shape
MsgBox TypeName(objChtDupl)

‘returns the same name for the duplicate copy — «Chart 5»
MsgBox objChtDupl.Name

‘change name of the duplicate copy
objChtDupl.Name = «Chart 6«

End Sub

Child Objects for the ChartObject Object: Above we have discussed: the ShapeRange object — use the ShapeRange PropertyobjChartObject.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 PropertyobjChartObject.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 propertyobjChartObject.Interior — to return the Interior object, to manipulate the chart element’s interior (inside area); Border Object — use the Border PropertyobjChartObject.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()
‘display & manipulate the chart data table — refer Image 2

’embedded chart
With Sheets(«Sheet1»).ChartObjects(1).Chart

‘add a data table to an embedded chart
.HasDataTable = True
‘do not display chart legend separately
.HasLegend = False

‘use the DataTable property of the Chart object to return a DataTable object
With .DataTable

‘include chart legend with the data table — set ShowLegendKey property to True so that the data table contains the legend
.ShowLegendKey = True

‘use the Font property of the DataTable object to return a Font object to manipulate the font
With .Font
.Name = «Arial«
.Size = 9
.Bold = False
.Color = RGB(0, 0, 255)
End With

‘data table not to have vertical cell borders
.HasBorderVertical = False
‘data table not to have horizontal cell borders
.HasBorderHorizontal = False
‘data table displayed with an outline border
.HasBorderOutline = True

‘use the Border property of the DataTable object to return a Border object to manipulate the border
With .Border
‘set linestyle as dotted line
.LineStyle = xlDot
‘set the weight
.Weight = xlThin
‘set the line color to red
.Color = vbRed
End With

‘use the Format property of the DataTable object to return a ChartFormat object which contains the line, fill & effect formatting for the data table
With .Format.Fill
‘sets the  fill color for the data table values
.ForeColor.RGB = RGB(230, 185, 184)
End With

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):
‘return name of a Chart object (embedded chart)
MsgBox Sheets(«Sheet1»).ChartObjects(1).Chart.Name

‘read-write for a ChartObject (embedded chart):
‘set name for a ChartObject (embedded chart)
Sheets(«Sheet1»).ChartObjects(1).Name = «QtrlySalesProfit«
‘return name for a ChartObject (embedded chart)
MsgBox Sheets(«Sheet1»).ChartObjects(1).Name

Name property is read-write for a Chart object (chart sheet):
‘set name for the first chart sheet
Charts(1).Name = «NewChartSheet«
‘return name of the first chart sheet
MsgBox Charts(1).Name

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
Sheets(«Sheet1»).ChartObjects(1).Chart.Walls.Border.ColorIndex = 3

‘individually format the side wall — set interior pattern to Checkerboard
Sheets(«Sheet1»).ChartObjects(1).Chart.SideWall.Interior.Pattern = xlPatternChecker

‘individually format the back wall — set interior color to blue
Sheets(«Sheet1»).ChartObjects(1).Chart.BackWall.Interior.Color = RGB(0, 0, 255)

‘set floor interior color to red
Sheets(«Sheet1»).ChartObjects(1).Chart.Floor.Interior.ColorIndex = 3

‘set floor thickness to 12
Sheets(«Sheet1»).ChartObjects(1).Chart.Floor.Thickness = 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)
Charts(«ChartSheet1»).Select
Charts(«ChartSheet2»).Select (False)

‘selects the 2 chart objects (chart sheets)
Charts(Array(«ChartSheet1», «ChartSheet2»)).Select

‘selects second embedded chart (ChartObject object) only:
Sheets(«Sheet1»).ChartObjects(1).Select
Sheets(«Sheet1»).ChartObjects(2).Select

‘selects the 2 embedded charts (ChartObject objects):
Sheets(«Sheet1»).Shapes.Range(Array(«EmbChart1», «EmbChart2»)).Select

‘to deselect the active ChartObject:
‘revert to the active cell
ActiveCell.Select
‘or go to cell A1
Range(«A1»).Select

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»
‘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(«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
Dim objCht As ChartObject
For Each objCht In Sheets(«Sheet9»).ChartObjects
objCht.Chart.PrintPreview
Next

‘Print all embedded charts in a sheet
Dim objCht As ChartObject
For Each objCht In Sheets(«Sheet9»).ChartObjects
objCht.Chart.PrintOut
Next

‘Printing a chart sheet — page setup & printout:

‘use the PageSetup object to manipulate page setup attributes viz. margin, paper size, header, footer, etc
With Charts(«ChartSheet»).PageSetup

‘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
.ChartSize = xlScreenSize
.CenterHeader = «Chart 1»
.RightFooter = «Tom Hiller»
.CenterVertically = False
.CenterHorizontally = False
.LeftMargin = Application.InchesToPoints(0.8)
.RightMargin = Application.InchesToPoints(0.8)
.TopMargin = Application.InchesToPoints(0.85)
.BottomMargin = Application.InchesToPoints(0.85)
.HeaderMargin = Application.InchesToPoints(0.25)
.FooterMargin = Application.InchesToPoints(0.25)
.Orientation = xlLandscape
.Draft = False
.PaperSize = xlPaperA4
.FirstPageNumber = xlAutomatic
.Zoom = 90
.PrintQuality = 600

End With

‘print out 1 copy of the chart sheet
Charts(«ChartSheet»).Activate
ActiveWindow.SelectedSheets.PrintOut Copies:=1, IgnorePrintAreas:=False

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:
Sheets(«Sheet1″).ChartObjects(1).Chart.ApplyDataLabels Type:=xlDataLabelsShowLabelAndPercent, LegendKey:=True, ShowValue:=True, Separator:=»/«

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 source data sheet

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

 
End Sub

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

Excel VBA Tutorial about how to create bar charts with macrosIn this VBA Tutorial, you learn how to create a clustered or stacked bar chart with macros.

This VBA Tutorial is accompanied by Excel workbooks containing the macros I use in the examples below. You can get immediate access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.

Use the following Table of Contents to navigate to the section you’re interested in.

Related VBA and Macro Tutorials

The following VBA and Macro Tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • If you’re a beginner, learn how to start working with macros here.
    • Understand essential VBA terms here.
    • Learn how to enable or disable macros here.
    • Learn about the Visual Basic Editor here.
    • Learn how to refer to objects here.
    • Learn how to create references to cell range here.
    • Learn about Sub procedures here.
    • Learn how to work with properties here.
    • Learn how to work with methods here.
    • Learn how to create and assign values to variables here.
    • Learn about data types here.
  • Practical VBA applications and macro examples:
    • Learn how to work with worksheets here.
    • Learn how to find the last row in a worksheet here.
    • Learn how to find the last column in a worksheet here.
    • Learn how to specify the width of a column here.
    • Learn how to check if a cell is empty here.
    • Learn how to delete a sheet here.
  • Tutorials about other useful topics:
    • Learn how to import and consolidate data using Power Query here.

You can find additional VBA and Macro Tutorials in the Archives.

#1: Create an embedded clustered or stacked bar chart (without selecting the source data range)

VBA code to create an embedded clustered or stacked bar chart (without selecting the source data range)

To create an embedded clustered or stacked bar chart (without selecting the source data range) using VBA, use a macro with the following statement structure:

Dim myChart As Chart
Set myChart = Worksheet.Shapes.AddChart2(Style:=-1, XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height, NewLayout:=Boolean).Chart
myChart.SetSourceData Source:=SourceDataRange

Process followed by VBA to create an embedded clustered or stacked bar chart (without selecting the source data range)

To create an embedded clustered or stacked bar chart (without selecting the source data range), follow these steps within your VBA code:

  1. Declare an object variable (myChart) to represent the newly-created clustered or stacked bar chart.
  2. Create a clustered or stacked bar chart with the Shapes.AddChart2 method.
  3. Assign the Chart object representing the newly-created clustered or stacked bar chart to the myChart object variable.
  4. Specify the source data for the newly-created clustered or stacked bar chart with the Chart.SetSourceData method.

Declare object variable > create bar chart > assign chart to object variable > specify source data

VBA statement explanation

Line #1: Dim myChart As Chart

  1. Item: Dim.
    • VBA construct: Dim statement.
    • Description: The Dim statement declares the myChart object variable and allocates storage space.
  2. Item: myChart.
    • VBA construct: Object variable.
    • Description: myChart is an object variable of the Chart object data type. The purpose of myChart is to represent a reference to the newly-created clustered or stacked bar chart.
  3. Item: Chart.
    • VBA construct: type part of the Dim statement.
    • Description: Chart is the data type of the declared variable. In other words, myChart is declared as of the Chart object data type.

Line #2: Set myChart = Worksheet.Shapes.AddChart2(Style:=-1, XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height, NewLayout:=Boolean).Chart

  1. Item: Set.
    • VBA construct: Set statement.
    • Description: Set assigns an object reference to an object variable. For purposes of this macro structure:
      • myChart is the object variable to which an object reference is assigned to.
      • The object reference assigned to myChart is the Chart object representing the newly-created clustered or stacked bar chart, as returned by the Shape.Chart property.
  2. Item: myChart.
    • VBA construct: objectvar part of the Set statement, variable part of the assignment (=) operator, and object variable of the Chart object data type.
    • Description: myChart represents a reference to the newly-created clustered or stacked bar chart. Within the Set statement, myChart is the object variable to which an object reference is assigned to.
  3. Item: =.
    • VBA construct: Assignment operator.
    • Description: The assignment operator assigns a value to a variable. For purposes of this macro structure:
      • myChart is the object variable to which the value is assigned to.
      • The value assigned to myChart is the Chart object representing the newly-created clustered or stacked bar chart, as returned by the Shape.Chart property.
  4. Item: Worksheet.
    • VBA construct: Worksheet object.
    • Description: Worksheet represents the worksheet where you insert the newly-created clustered or stacked bar chart.

      Use constructs such as the Application.ActiveSheet property or the Workbook.Worksheets property to return the appropriate Worksheet object. If you explicitly declare an object variable to represent Worksheet, use the Worksheet object data type.

  5. Item: Shapes.
    • VBA construct: Worksheet.Shapes property.
    • Description: The Worksheet.Shapes property returns a Shapes collection representing all the shapes within Worksheet. Each Shape object within the Shapes collection represents an object in the drawing lawyer of the worksheet.
  6. Item: AddChart2.
    • VBA construct: Shapes.AddChart2 method.
    • Description: The Shapes.AddChart2 method creates a chart. Shapes.AddChart2 returns a Shape object representing the newly-created clustered or stacked bar chart. This Shape object is added to the Shapes collection representing all the shapes within Worksheet.

      The AddChart2 method was introduced in Excel 2013 and isn’t backward compatible. To create a chart in Excel 2007 or Excel 2010 using VBA, use the Shapes.AddChart method. For an explanation and example of how to work with the AddChart method, please refer to the appropriate section below.

  7. Item: Style:=-1.
    • VBA construct: Style parameter of the Shapes.AddChart2 method.
    • Description: The Style parameter of Shapes.AddChart2 specifies the style of the newly-created clustered or stacked bar chart.

      When you set Style to -1 (as in this macro structure), the newly-created chart gets the default style for the applicable clustered or stacked bar chart type.

  8. Item: XlChartType:=ChartType.
    • VBA construct: XlChartType parameter of the Shapes.AddChart2 method.
    • Description: The XlChartType parameter of Shapes.AddChart2 specifies the type of the newly-created clustered or stacked bar chart. You can set XlChartType to any of the built-in constants within the XlChartType enumeration. For purposes of creating a clustered or stacked bar chart, use one of the following built-in constants or values:
      • xlPyramidBarClustered (or 109) to create a clustered pyramid bar chart.
      • xlPyramidBarStacked (or 110) to create a stacked pyramid bar chart.
      • xlPyramidBarStacked100 (or 111) to create a 100% stacked pyramid bar chart.
      • xlBarClustered (or 57) to create a clustered bar chart.
      • xlBarStacked (or 58) to create a stacked bar chart.
      • xlBarStacked100 (or 59) to create a 100% stacked bar chart.
      • xlConeBarClustered (or 102) to create a clustered cone bar chart.
      • xlConeBarStacked (or 103) to create a stacked cone bar chart.
      • xlConeBarStacked100 (or 104) to create a 100% stacked cone bar chart.
      • xlCylinderBarClustered (or 95) to create a clustered cylinder bar chart.
      • xlCylinderBarStacked (or 96) to create a stacked cylinder bar chart.
      • xlCylinderBarStacked100 (or 97) to create a 100% stacked cylinder bar chart.
  9. Item: Left:=ChartDestination.Cells(1).Left.
    • VBA construct: Left parameter of the Shapes.AddChart2 method.
    • Description: The Left parameter of Shapes.AddChart2 specifies the position, in points, of the newly-created clustered or stacked bar chart’s left edge relative to the anchor which, in this case, is the left edge of column A. For purposes of this macro structure, Left’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Cells and Range.Item properties (Cells(1)) return a Range object representing the first (top-left corner) cell within ChartDestination.
      • The Range.Left property returns a value representing the distance, in points, between the left edge of column A and the left edge of ChartDestination.

      Because of the above, “ChartDestination.Cells(1).Left” sets the left edge of the newly-created clustered or stacked bar chart to be at the left edge of ChartDestination.

  10. Item: Top:=ChartDestination.Cells(1).Top.
    • VBA construct: Top parameter of the Shapes.AddChart2 method.
    • Description: The Top parameter of Shapes.AddChart2 specifies the position, in points, of the newly-created clustered or stacked bar chart’s top edge relative to the anchor which, in this case, is the top edge of row 1. For purposes of this macro structure, Top’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Cells and Range.Item properties (Cells(1)) return a Range object representing the first (top-left corner) cell within ChartDestination.
      • The Range.Top property returns a value representing the distance, in points, between the top edge of row 1 and the top edge of ChartDestination.

      Because of the above, “ChartDestination.Cells(1).Top” sets the top edge of the newly-created clustered or stacked bar chart to be at the top edge of ChartDestination.

  11. Item: Width:=ChartDestination.Width.
    • VBA construct: Width parameter of the Shapes.AddChart2 method.
    • Description: The Width parameter of Shapes.AddChart2 specifies the width, in points, of the newly-created clustered or stacked bar chart. For purposes of this macro structure, Width’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Width property returns a value representing the width, in points, of ChartDestination.

      Because of the above, “ChartDestination.Width” sets the width of the newly-created clustered or stacked bar chart to be the width of ChartDestination.

  12. Item: Height:=ChartDestination.Height.
    • VBA construct: Height parameter of the Shapes.AddChart2 method.
    • Description: The Height parameter of Shapes.AddChart2 specifies the height, in points, of the newly-created clustered or stacked bar chart. For purposes of this macro structure, Height’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Height property returns a value representing the height, in points, of ChartDestination.

      Because of the above, “ChartDestination.Height” sets the height of the newly-created clustered or stacked bar chart to be the height of ChartDestination.

  13. Item: NewLayout:=Boolean.
    • VBA construct: NewLayout parameter of the Shapes.AddChart2 method.
    • Description: The NewLayout parameter of Shapes.AddChart2 specifies whether the newly-created clustered or stacked bar chart is inserted by using certain dynamic formatting rules. The 2 main consequences of applying these dynamic formatting rules are that:
      • The chart title is displayed.
      • The legend is displayed only if the bar chart contains multiple series.

      You specify NewLayout’s value as a Boolean (True or False).

      • If you set NewLayout to True, the new dynamic formatting rules apply.
      • If you set NewLayout to False, the new dynamic formatting rules don’t apply.
  14. Item: Chart.
    • VBA construct: Shape.Chart property.
    • Description: The Shape.Chart property returns a Chart object representing the chart contained within the shape. For purposes of this macro structure, the Chart object returned by Shape.Chart represents the newly-created clustered or stacked bar chart.
  15. Item: Worksheet.Shapes.AddChart2(Style:=-1, XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height, NewLayout:=Boolean).Chart.
    • VBA construct: objectexpression part of the Set statement and value part of the assignment (=) operator.
    • Description: This expression returns a Chart object representing the newly-created clustered or stacked bar chart. This Chart object is assigned to myChart.

Line #3: myChart.SetSourceData Source:=SourceDataRange

  1. Item: myChart.
    • VBA construct: Object variable of the Chart object data type.
    • Description: myChart represents a reference to the newly-created clustered or stacked bar chart.
  2. Item: SetSourceData.
    • VBA construct: Chart.SetSourceData method.
    • Description: The Chart.SetSourceData method sets the source data range for myChart.
  3. Item: Source:=SourceDataRange.
    • VBA construct: Source parameter of the Chart.SetSourceData method.
    • Description: The Source parameter of Chart.SetSourceData specifies the cell range containing the source data for myChart.

      SourceDataRange is a Range object representing the cell range that contains the source data for myChart.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent SourceDataRange, use the Range object data type.

Macro example to create an embedded clustered or stacked bar chart (without selecting the source data range)

The following macro example creates an embedded clustered bar chart (myChart) in the worksheet named “embedded clustered bar chart” (myWorksheet) of the workbook containing the macro (ThisWorkbook). For these purposes:

  • The source data (mySourceData) is contained in cells A5 to F10 of myWorksheet; and
  • The clustered bar chart is located over cells H5 to M24 of myWorksheet (myChartDestination).
Sub createEmbeddedClusteredBarChart()
    'source: https://powerspreadsheets.com/
    'creates an embedded clustered bar chart (without selecting the source data range)
    'for further information: https://powerspreadsheets.com/vba-create-bar-chart/

    'declare object variables to hold references to worksheet, source data cell range, created bar chart, and destination cell range
    Dim myWorksheet As Worksheet
    Dim mySourceData As Range
    Dim myChart As Chart
    Dim myChartDestination As Range

    'identify worksheet containing source data and created bar chart
    Set myWorksheet = ThisWorkbook.Worksheets("embedded clustered bar chart")

    With myWorksheet

        'identify source data
        Set mySourceData = .Range("A5:F10")

        'identify chart location
        Set myChartDestination = .Range("H5:M24")

        'create bar chart
        Set myChart = .Shapes.AddChart2(Style:=-1, XlChartType:=xlBarClustered, Left:=myChartDestination.Cells(1).Left, Top:=myChartDestination.Cells(1).Top, Width:=myChartDestination.Width, Height:=myChartDestination.Height, NewLayout:=False).Chart

    End With

    'set source data for created bar chart
    myChart.SetSourceData Source:=mySourceData

End Sub

Effects of executing macro example to create an embedded clustered or stacked bar chart (without selecting the source data range)

The following image illustrates the results of executing the macro example. An embedded clustered bar chart is created over cells H5 to M24. The source data for this chart is in cells A5 to F10.

Clustered bar chart created with a macro

#2: Create an embedded clustered or stacked bar chart (selecting the source data range)

VBA code to create an embedded clustered or stacked bar chart (selecting the source data range)

To create an embedded clustered or stacked bar chart (selecting the source data range) using VBA, use a macro with the following statement structure:

SourceDataWorksheet.Activate
SourceDataRange.Select
DestinationWorksheet.Shapes.AddChart2 Style:=-1, XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height, NewLayout:=Boolean

Process followed by VBA to create an embedded clustered or stacked bar chart (selecting the source data range)

To create an embedded clustered or stacked bar chart (selecting the source data range), follow these steps within your VBA code:

  1. Activate the worksheet containing the source data.
  2. Select the cell range containing the source data.
  3. Create a clustered or stacked bar chart with the Shapes.AddChart2 method.

Activate worksheet with source data > select source data > create bar chart

VBA statement explanation

Line #1: SourceDataWorksheet.Activate

  1. Item: SourceDataWorksheet.
    • VBA construct: Worksheet object.
    • Description: SourceDataWorksheet represents the worksheet where the cell range containing the source data for the clustered or stacked bar chart is located.

      Use constructs such as the Workbook.Worksheets property to return the appropriate Worksheet object. If you explicitly declare an object variable to represent SourceDataWorksheet, use the Worksheet object data type.

  2. Item: Activate.
    • VBA construct: Worksheet.Activate method.
    • Description: The Activate method makes SourceDataWorksheet the active sheet.

      The main reason for including this statement is that, generally, you can’t select a cell on a worksheet that isn’t active. If SourceDataWorksheet is already the active worksheet, you may omit this statement.

Line #2: SourceDataRange.Select

  1. Item: SourceDataRange.
    • VBA construct: Range object.
    • Description: Range object representing the cell range that contains the source data for the clustered or stacked bar chart.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent SourceDataRange, use the Range object data type.

  2. Item: Select.
    • VBA construct: Range.Select method.
    • Description: The Select method selects SourceDataRange.

Line #3: ChartDestinationWorksheet.Shapes.AddChart2 Style:=-1, XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height, NewLayout:=Boolean

  1. Item: ChartDestinationWorksheet.
    • VBA construct: Worksheet object.
    • Description: ChartDestinationWorksheet represents the worksheet where you insert the newly-created clustered or stacked bar chart.

      Use constructs such as the Application.ActiveSheet property or the Workbook.Worksheets property to return the appropriate Worksheet object.

  2. Item: Shapes.
    • VBA construct: Worksheet.Shapes property.
    • Description: The Worksheet.Shapes property returns a Shapes collection representing all the shapes within ChartDestinationWorksheet. Each Shape object within the Shapes collection represents an object in the drawing lawyer of the worksheet.
  3. Item: AddChart2.
    • VBA construct: Shapes.AddChart2 method.
    • Description: The Shapes.AddChart2 method creates a chart. Shapes.AddChart2 returns a Shape object representing the newly-created clustered or stacked bar chart. This Shape object is added to the Shapes collection representing all the shapes within ChartDestinationWorksheet.

      The AddChart2 method was introduced in Excel 2013 and isn’t backward compatible. To create a chart in Excel 2007 or Excel 2010 using VBA, use the Shapes.AddChart method. For an explanation and example of how to work with the AddChart method, please refer to the appropriate section below.

  4. Item: Style:=-1.
    • VBA construct: Style parameter of the Shapes.AddChart2 method.
    • Description: The Style parameter of Shapes.AddChart2 specifies the style of the newly-created clustered or stacked bar chart.

      When you set Style to -1 (as in this macro structure), the newly-created chart gets the default style for the applicable clustered or stacked bar chart type.

  5. Item: XlChartType:=ChartType.
    • VBA construct: XlChartType parameter of the Shapes.AddChart2 method.
    • Description: The XlChartType parameter of Shapes.AddChart2 specifies the type of the newly-created clustered or stacked bar chart. You can set XlChartType to any of the built-in constants within the XlChartType enumeration. For purposes of creating a clustered or stacked bar chart, use one of the following built-in constants or values:
      • xlPyramidBarClustered (or 109) to create a clustered pyramid bar chart.
      • xlPyramidBarStacked (or 110) to create a stacked pyramid bar chart.
      • xlPyramidBarStacked100 (or 111) to create a 100% stacked pyramid bar chart.
      • xlBarClustered (or 57) to create a clustered bar chart.
      • xlBarStacked (or 58) to create a stacked bar chart.
      • xlBarStacked100 (or 59) to create a 100% stacked bar chart.
      • xlConeBarClustered (or 102) to create a clustered cone bar chart.
      • xlConeBarStacked (or 103) to create a stacked cone bar chart.
      • xlConeBarStacked100 (or 104) to create a 100% stacked cone bar chart.
      • xlCylinderBarClustered (or 95) to create a clustered cylinder bar chart.
      • xlCylinderBarStacked (or 96) to create a stacked cylinder bar chart.
      • xlCylinderBarStacked100 (or 97) to create a 100% stacked cylinder bar chart.
  6. Item: Left:=ChartDestination.Cells(1).Left.
    • VBA construct: Left parameter of the Shapes.AddChart2 method.
    • Description: The Left parameter of Shapes.AddChart2 specifies the position, in points, of the newly-created clustered or stacked bar chart’s left edge relative to the anchor which, in this case, is the left edge of column A. For purposes of this macro structure, Left’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Cells and Range.Item properties (Cells(1)) return a Range object representing the first (top-left corner) cell within ChartDestination.
      • The Range.Left property returns a value representing the distance, in points, between the left edge of column A and the left edge of ChartDestination.

      Because of the above, “ChartDestination.Cells(1).Left” sets the left edge of the newly-created clustered or stacked bar chart to be at the left edge of ChartDestination.

  7. Item: Top:=ChartDestination.Cells(1).Top.
    • VBA construct: Top parameter of the Shapes.AddChart2 method.
    • Description: The Top parameter of Shapes.AddChart2 specifies the position, in points, of the newly-created clustered or stacked bar chart’s top edge relative to the anchor which, in this case, is the top edge of row 1. For purposes of this macro structure, Top’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Cells and Range.Item properties (Cells(1)) return a Range object representing the first (top-left corner) cell within ChartDestination.
      • The Range.Top property returns a value representing the distance, in points, between the top edge of row 1 and the top edge of ChartDestination.

      Because of the above, “ChartDestination.Cells(1).Top” sets the top edge of the newly-created clustered or stacked bar chart to be at the top edge of ChartDestination.

  8. Item: Width:=ChartDestination.Width.
    • VBA construct: Width parameter of the Shapes.AddChart2 method.
    • Description: The Width parameter of Shapes.AddChart2 specifies the width, in points, of the newly-created clustered or stacked bar chart. For purposes of this macro structure, Width’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Width property returns a value representing the width, in points, of ChartDestination.

      Because of the above, “ChartDestination.Width” sets the width of the newly-created clustered or stacked bar chart to be the width of ChartDestination.

  9. Item: Height:=ChartDestination.Height.
    • VBA construct: Height parameter of the Shapes.AddChart2 method.
    • Description: The Height parameter of Shapes.AddChart2 specifies the height, in points, of the newly-created clustered or stacked bar chart. For purposes of this macro structure, Height’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Height property returns a value representing the height, in points, of ChartDestination.

      Because of the above, “ChartDestination.Height” sets the height of the newly-created clustered or stacked bar chart to be the height of ChartDestination.

  10. Item: NewLayout:=Boolean.
    • VBA construct: NewLayout parameter of the Shapes.AddChart2 method.
    • Description: The NewLayout parameter of Shapes.AddChart2 specifies whether the newly-created clustered or stacked bar chart is inserted by using certain dynamic formatting rules. The 2 main consequences of applying these dynamic formatting rules are that:
      • The chart title is displayed.
      • The legend is displayed only if the bar chart contains multiple series.

      You specify NewLayout’s value as a Boolean (True or False).

      • If you set NewLayout to True, the new dynamic formatting rules apply.
      • If you set NewLayout to False, the new dynamic formatting rules don’t apply.

Macro example to create an embedded clustered or stacked bar chart (selecting the source data range)

The following macro example creates an embedded stacked bar chart (myChart) in the worksheet named “embedded stacked bar chart” (myWorksheet) of the workbook containing the macro (ThisWorkbook). For these purposes:

  • The source data (mySourceData) is contained in cells A5 to F10 of myWorksheet; and
  • The clustered bar chart is located over cells H5 to M24 of myWorksheet (myChartDestination).
Sub createEmbeddedStackedBarChart()
    'source: https://powerspreadsheets.com/
    'creates an embedded stacked bar chart (selecting the source data range)
    'for further information: https://powerspreadsheets.com/vba-create-bar-chart/

    'declare object variables to hold references to worksheet, source data cell range, created bar chart, and destination cell range
    Dim myWorksheet As Worksheet
    Dim mySourceData As Range
    Dim myChart As Chart
    Dim myChartDestination As Range

    'identify worksheet containing source data and created bar chart
    Set myWorksheet = ThisWorkbook.Worksheets("embedded stacked bar chart")

    'identify source data
    Set mySourceData = myWorksheet.Range("A5:F10")

    'activate worksheet and select source data
    myWorksheet.Activate
    mySourceData.Select

    With myWorksheet

        'identify chart location
        Set myChartDestination = .Range("H5:M24")

        'create bar chart
        .Shapes.AddChart2 Style:=-1, XlChartType:=xlBarStacked, Left:=myChartDestination.Cells(1).Left, Top:=myChartDestination.Cells(1).Top, Width:=myChartDestination.Width, Height:=myChartDestination.Height, NewLayout:=False

    End With

End Sub

Effects of executing macro example to create an embedded clustered or stacked bar chart (selecting the source data range)

The following image illustrates the results of executing the macro example. An embedded stacked bar chart is created over cells H5 to M24. The source data for this chart is in cells A5 to F10.

Stacked bar chart created with a macro

#3: Create an embedded clustered or stacked bar chart (compatible with Excel 2007 and Excel 2010)

VBA code to create an embedded clustered or stacked bar chart (compatible with Excel 2007 and Excel 2010)

To create an embedded clustered or stacked bar chart in Excel 2007 or Excel 2010 using VBA, use a macro with the following statement structure:

Dim myChart As Chart
Set myChart = Worksheet.Shapes.AddChart(XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height).Chart
myChart.SetSourceData Source:=SourceDataRange

Process followed by VBA to create an embedded clustered or stacked bar chart (compatible with Excel 2007 and Excel 2010)

To create an embedded clustered or stacked bar chart (using VBA code that’s compatible with Excel 2007 and Excel 2010), follow these steps within your VBA code:

  1. Declare an object variable (myChart) to represent the newly-created clustered or stacked bar chart.
  2. Create a clustered or stacked bar chart with the Shapes.AddChart method.
  3. Assign the Chart object representing the newly-created clustered or stacked bar chart to the myChart object variable.
  4. Specify the source data for the newly-created clustered or stacked bar chart with the Chart.SetSourceData method.

Declare object variable > create bar chart > assign chart to object variable > specify source data

VBA statement explanation

Line #1: Dim myChart As Chart

  1. Item: Dim.
    • VBA construct: Dim statement.
    • Description: The Dim statement declares the myChart object variable and allocates storage space.
  2. Item: myChart.
    • VBA construct: Object variable.
    • Description: myChart is an object variable of the Chart object data type. The purpose of myChart is to represent a reference to the newly-created clustered or stacked bar chart.
  3. Item: Chart.
    • VBA construct: type part of the Dim statement.
    • Description: Chart is the data type of the declared variable. In other words, myChart is declared as of the Chart object data type.

Line #2: Set myChart = Worksheet.Shapes.AddChart(XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height).Chart

  1. Item: Set.
    • VBA construct: Set statement.
    • Description: Set assigns an object reference to an object variable. For purposes of this macro structure:
      • myChart is the object variable to which an object reference is assigned to.
      • The object reference assigned to myChart is the Chart object representing the newly-created clustered or stacked bar chart, as returned by the Shape.Chart property.
  2. Item: myChart.
    • VBA construct: objectvar part of the Set statement, variable part of the assignment (=) operator, and object variable of the Chart object data type.
    • Description: myChart represents a reference to the newly-created clustered or stacked bar chart. Within the Set statement, myChart is the object variable to which an object reference is assigned to.
  3. Item: =.
    • VBA construct: Assignment operator.
    • Description: The assignment operator assigns a value to a variable. For purposes of this macro structure:
      • myChart is the object variable to which the value is assigned to.
      • The value assigned to myChart is the Chart object representing the newly-created clustered or stacked bar chart, as returned by the Shape.Chart property.
  4. Item: Worksheet.
    • VBA construct: Worksheet object.
    • Description: Worksheet represents the worksheet where you insert the newly-created clustered or stacked bar chart.

      Use constructs such as the Application.ActiveSheet property or the Workbook.Worksheets property to return the appropriate Worksheet object. If you explicitly declare an object variable to represent Worksheet, use the Worksheet object data type.

  5. Item: Shapes.
    • VBA construct: Worksheet.Shapes property.
    • Description: The Worksheet.Shapes property returns a Shapes collection representing all the shapes within Worksheet. Each Shape object within the Shapes collection represents an object in the drawing lawyer of the worksheet.
  6. Item: AddChart.
    • VBA construct: Shapes.AddChart method.
    • Description: The Shapes.AddChart method creates a chart. Shapes.AddChart returns a Shape object representing the newly-created clustered or stacked bar chart. This Shape object is added to the Shapes collection representing all the shapes within Worksheet.

      In Excel 2013, Microsoft introduced the AddChart2 method. AddChart2 is generally more powerful and easier to work with than AddChart. However, AddChart continues to be supported and, therefore, macros that use AddChart work appropriately in Excel 2007 and later.

  7. Item: XlChartType:=ChartType.
    • VBA construct: XlChartType parameter of the Shapes.AddChart method.
    • Description: The XlChartType parameter of Shapes.AddChart specifies the type of the newly-created clustered or stacked bar chart. You can set XlChartType to any of the built-in constants within the XlChartType enumeration. For purposes of creating a clustered or stacked bar chart, use one of the following built-in constants or values:
      • xlPyramidBarClustered (or 109) to create a clustered pyramid bar chart.
      • xlPyramidBarStacked (or 110) to create a stacked pyramid bar chart.
      • xlPyramidBarStacked100 (or 111) to create a 100% stacked pyramid bar chart.
      • xlBarClustered (or 57) to create a clustered bar chart.
      • xlBarStacked (or 58) to create a stacked bar chart.
      • xlBarStacked100 (or 59) to create a 100% stacked bar chart.
      • xlConeBarClustered (or 102) to create a clustered cone bar chart.
      • xlConeBarStacked (or 103) to create a stacked cone bar chart.
      • xlConeBarStacked100 (or 104) to create a 100% stacked cone bar chart.
      • xlCylinderBarClustered (or 95) to create a clustered cylinder bar chart.
      • xlCylinderBarStacked (or 96) to create a stacked cylinder bar chart.
      • xlCylinderBarStacked100 (or 97) to create a 100% stacked cylinder bar chart.
  8. Item: Left:=ChartDestination.Cells(1).Left.
    • VBA construct: Left parameter of the Shapes.AddChart method.
    • Description: The Left parameter of Shapes.AddChart specifies the position, in points, of the newly-created clustered or stacked bar chart’s left edge relative to the anchor which, in this case, is the left edge of column A. For purposes of this macro structure, Left’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Cells and Range.Item properties (Cells(1)) return a Range object representing the first (top-left corner) cell within ChartDestination.
      • The Range.Left property returns a value representing the distance, in points, between the left edge of column A and the left edge of ChartDestination.

      Because of the above, “ChartDestination.Cells(1).Left” sets the left edge of the newly-created clustered or stacked bar chart to be at the left edge of ChartDestination.

  9. Item: Top:=ChartDestination.Cells(1).Top.
    • VBA construct: Top parameter of the Shapes.AddChart method.
    • Description: The Top parameter of Shapes.AddChart specifies the position, in points, of the newly-created clustered or stacked bar chart’s top edge relative to the anchor which, in this case, is the top edge of row 1. For purposes of this macro structure, Top’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Cells and Range.Item properties (Cells(1)) return a Range object representing the first (top-left corner) cell within ChartDestination.
      • The Range.Top property returns a value representing the distance, in points, between the top edge of row 1 and the top edge of ChartDestination.

      Because of the above, “ChartDestination.Cells(1).Top” sets the top edge of the newly-created clustered or stacked bar chart to be at the top edge of ChartDestination.

  10. Item: Width:=ChartDestination.Width.
    • VBA construct: Width parameter of the Shapes.AddChart method.
    • Description: The Width parameter of Shapes.AddChart specifies the width, in points, of the newly-created clustered or stacked bar chart. For purposes of this macro structure, Width’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Width property returns a value representing the width, in points, of ChartDestination.

      Because of the above, “ChartDestination.Width” sets the width of the newly-created clustered or stacked bar chart to be the width of ChartDestination.

  11. Item: Height:=ChartDestination.Height.
    • VBA construct: Height parameter of the Shapes.AddChart method.
    • Description: The Height parameter of Shapes.AddChart specifies the height, in points, of the newly-created clustered or stacked bar chart. For purposes of this macro structure, Height’s value is determined as follows:
      • ChartDestination is a Range object representing the cells where you want the newly-created clustered or stacked bar chart to be located.

        You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent ChartDestination, use the Range object data type.

      • The Range.Height property returns a value representing the height, in points, of ChartDestination.

      Because of the above, “ChartDestination.Height” sets the height of the newly-created clustered or stacked bar chart to be the height of ChartDestination.

  12. Item: Chart.
    • VBA construct: Shape.Chart property.
    • Description: The Shape.Chart property returns a Chart object representing the chart contained within the shape. For purposes of this macro structure, the Chart object returned by Shape.Chart represents the newly-created clustered or stacked bar chart.
  13. Item: Worksheet.Shapes.AddChart(XlChartType:=ChartType, Left:=ChartDestination.Cells(1).Left, Top:=ChartDestination.Cells(1).Top, Width:=ChartDestination.Width, Height:=ChartDestination.Height).Chart.
    • VBA construct: objectexpression part of the Set statement and value part of the assignment (=) operator.
    • Description: This expression returns a Chart object representing the newly-created clustered or stacked bar chart. This Chart object is assigned to myChart.

Line #3: myChart.SetSourceData Source:=SourceDataRange

  1. Item: myChart.
    • VBA construct: Object variable of the Chart object data type.
    • Description: myChart represents a reference to the newly-created clustered or stacked bar chart.
  2. Item: SetSourceData.
    • VBA construct: Chart.SetSourceData method.
    • Description: The Chart.SetSourceData method sets the source data range for myChart.
  3. Item: Source:=SourceDataRange.
    • VBA construct: Source parameter of the Chart.SetSourceData method.
    • Description: The Source parameter of Chart.SetSourceData specifies the cell range containing the source data for myChart.

      SourceDataRange is a Range object representing the cell range that contains the source data for myChart.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent SourceDataRange, use the Range object data type.

Macro example to create an embedded clustered or stacked bar chart (compatible with Excel 2007 and Excel 2010)

The following macro example creates an embedded clustered bar chart (myChart) in the worksheet named “embedded bar chart compatible” (myWorksheet) of the workbook containing the macro (ThisWorkbook). For these purposes:

  • The source data (mySourceData) is contained in cells A5 to F10 of myWorksheet; and
  • The clustered bar chart is located over cells H5 to M24 of myWorksheet (myChartDestination).

This macro is the rough equivalent to a previous example (createEmbeddedClusteredBarChart). The main difference between both macros is the VBA construct they rely on to create the embedded clustered bar chart.

  • createEmbeddedClusteredBarChart works with the Shapes.AddChart2 method. This method was introduced in Excel 2013 and isn’t backward-compatible. Therefore, the createEmbeddedClusteredBarChart doesn’t work appropriately in Excel 2007 or Excel 2010.
  • The following macro example works with the Shapes.AddChart method. This method is compatible with Excel 2007 and later. Therefore, this macro works appropriately with Excel 2007, Excel 2010, Excel 2013 and Excel 2016.

The resulting embedded clustered bar charts aren’t identical. One of the reasons for some of these differences is the fact that the AddChart2 method accepts some additional parameters (particularly Style and NewLayout) that have no direct equivalent in the AddChart method.

Sub createEmbeddedClusteredBarChart20072010()

    'source: https://powerspreadsheets.com/
    'creates an embedded clustered bar chart. Code is compatible with Excel 2007 and Excel 2010
    'for further information: https://powerspreadsheets.com/vba-create-bar-chart/

    'declare object variables to hold references to worksheet, source data cell range, created bar chart, and destination cell range
    Dim myWorksheet As Worksheet
    Dim mySourceData As Range
    Dim myChart As Chart
    Dim myChartDestination As Range

    'identify worksheet containing source data and created bar chart
    Set myWorksheet = ThisWorkbook.Worksheets("embedded bar chart compatible")

    With myWorksheet

        'identify source data
        Set mySourceData = .Range("A5:F10")

        'identify chart location
        Set myChartDestination = .Range("H5:M24")

        'create bar chart
        Set myChart = .Shapes.AddChart(XlChartType:=xlBarClustered, Left:=myChartDestination.Cells(1).Left, Top:=myChartDestination.Cells(1).Top, Width:=myChartDestination.Width, Height:=myChartDestination.Height).Chart

    End With

    'set source data for created bar chart
    myChart.SetSourceData Source:=mySourceData
End Sub

Effects of executing macro example to create an embedded clustered or stacked bar chart (compatible with Excel 2007 and Excel 2010)

The following image illustrates the results of executing the macro example. An embedded clustered bar chart is created over cells H5 to M24. The source data for this chart is in cells A5 to F10.

Clustered bar chart created with a macro compatible with Excel 2007 and Excel 2010

#4: Create a clustered or stacked bar chart in a chart sheet

VBA code to create a clustered or stacked bar chart in a chart sheet

To create a clustered or stacked bar chart in a chart sheet using VBA, use a macro with the following statement structure:

Dim myChart As Chart
Set myChart = Charts.Add2(Before:=BeforeSheet, After:=AfterSheet, NewLayout:=Boolean)
With myChart
    .SetSourceData Source:=SourceDataRange
    .ChartType = ChartTypeValue
End With

Process followed by VBA to create a clustered or stacked bar chart in a chart sheet

To create a clustered or stacked bar chart in a chart sheet, follow these steps within your VBA code:

  1. Declare an object variable (myChart) to represent the newly-created clustered or stacked bar chart.
  2. Create a chart with the Charts.Add2 method.
  3. Assign the Chart object representing the newly-created chart to the myChart object variable.
  4. Specify the source data for the newly-created chart with the Chart.SetSourceData method.
  5. Specify that the newly-created chart is a clustered or stacked bar chart with the Chart.ChartType property.

Declare object variable > create chart > assign chart to object variable > specify source data > specify chart type as bar chart

VBA statement explanation

Line #1: Dim myChart As Chart

  1. Item: Dim.
    • VBA construct: Dim statement.
    • Description: The Dim statement declares the myChart object variable and allocates storage space.
  2. Item: myChart.
    • VBA construct: Object variable.
    • Description: myChart is an object variable of the Chart object data type. The purpose of myChart is to represent a reference to the newly-created clustered or stacked bar chart.
  3. Item: Chart.
    • VBA construct: type part of the Dim statement.
    • Description: Chart is the data type of the declared variable. In other words, myChart is declared as of the Chart object data type.

Line #2: Set myChart = Charts.Add2(Before:=BeforeSheet, After:=AfterSheet, NewLayout:=Boolean)

  1. Item: Set.
    • VBA construct: Set statement.
    • Description: Set assigns an object reference to an object variable. For purposes of this macro structure:
      • myChart is the object variable to which an object reference is assigned to.
      • The object reference assigned to myChart is the Chart object representing the newly-created clustered or stacked bar chart, as returned by the Charts.Add2 method.
  2. Item: myChart.
    • VBA construct: objectvar part of the Set statement, variable part of the assignment (=) operator, and object variable of the Chart object data type.
    • Description: myChart represents a reference to the newly-created clustered or stacked bar chart. Within the Set statement, myChart is the object variable to which an object reference is assigned to.
  3. Item: =.
    • VBA construct: Assignment operator.
    • Description: The assignment operator assigns a value to a variable. For purposes of this macro structure:
      • myChart is the object variable to which the value is assigned to.
      • The value assigned to myChart is the Chart object representing the newly-created clustered or stacked bar chart, as returned by the Charts.Add2 method.
  4. Item: Charts.
    • VBA construct: Charts collection.
    • Description: The Charts object is a collection representing all the chart sheets within the applicable workbook. Each chart sheet is represented by a Chart object.
  5. Item: Add2.
    • VBA construct: Charts.Add2 method.
    • Description: The Add2 method creates a new chart sheet and returns a Chart object representing this newly-created chart sheet.
  6. Item: Before:=BeforeSheet, After:=AfterSheet.
    • VBA construct: Before and After parameters of the Charts.Add2 method.
    • Description: The Before and After parameters of Charts.Add2 specify the sheet before (in the case of Before) or after (in the case of After) which the newly-created chart sheet (containing the clustered or stacked bar chart) is added.

      You generally:

      • Only specify 1 of these parameters (Before or After); and
      • Identify the appropriate sheet (BeforeSheet or AfterSheet) as an object. For these purposes, you can rely on constructs such as the Workbook.Sheets, Workbook.Charts or Workbook.Worksheets properties.

      If you omit both Before and After, the newly-inserted chart sheet is located before the active sheet.

  7. Item: NewLayout:=Boolean.
    • VBA construct: NewLayout parameter of the Charts.Add2 method.
    • Description: The NewLayout parameter of Charts.Add2 specifies whether the newly-created clustered or stacked bar chart is inserted by using certain dynamic formatting rules. The 2 main consequences of applying these dynamic formatting rules are that:
      • The chart title is displayed.
      • The legend is displayed only if the bar chart contains multiple series.

      You specify NewLayout’s value as a Boolean (True or False).

      • If you set NewLayout to True, the new dynamic formatting rules apply.
      • If you set NewLayout to False, the new dynamic formatting rules don’t apply.

Lines #3 and #6: With myChart | End With

  1. Item: With… End With.
    • VBA construct: With… End With statement.
    • Description: Statements within the With… End With statement are executed on the Chart object represented by myChart.

Line #4: .SetSourceData Source:=SourceDataRange

  1. Item: SetSourceData.
    • VBA construct: Chart.SetSourceData method.
    • Description: The Chart.SetSourceData method sets the source data range for myChart.
  2. Item: Source:=SourceDataRange.
    • VBA construct: Source parameter of the Chart.SetSourceData method.
    • Description: The Source parameter of Chart.SetSourceData specifies the cell range containing the source data for myChart.

      SourceDataRange is a Range object representing the cell range that contains the source data for myChart.

      You can usually return a Range object with constructs such as the Worksheet.Range, Worksheet.Cells (with Range.Item), Range.Offset or Range.Resize properties. If you explicitly declare an object variable to represent SourceDataRange, use the Range object data type.

Line #5: .ChartType = ChartTypeValue

  1. Item: ChartType.
    • VBA construct: Chart.ChartType property.
    • Description: Chart.ChartType sets the type of a chart.
  2. Item: =.
    • VBA construct: Assignment operator.
    • Description: The assignment operator assigns a value to a property. For purposes of this macro structure:
      • The Chart.ChartType property is the property to which the value is assigned.
      • The value assigned to ChartType is the value represented by ChartTypeValue.
  3. Item: ChartTypeValue.
    • VBA construct: Built-in constant or value from the XlChartType enumeration.
    • Description: The built-in constants or values from the XlChartType enumeration specify the chart type of the newly-created clustered or stacked bar chart. For these purposes, use one of the following built-in constants or values:
      • xlPyramidBarClustered (or 109) to create a clustered pyramid bar chart.
      • xlPyramidBarStacked (or 110) to create a stacked pyramid bar chart.
      • xlPyramidBarStacked100 (or 111) to create a 100% stacked pyramid bar chart.
      • xlBarClustered (or 57) to create a clustered bar chart.
      • xlBarStacked (or 58) to create a stacked bar chart.
      • xlBarStacked100 (or 59) to create a 100% stacked bar chart.
      • xlConeBarClustered (or 102) to create a clustered cone bar chart.
      • xlConeBarStacked (or 103) to create a stacked cone bar chart.
      • xlConeBarStacked100 (or 104) to create a 100% stacked cone bar chart.
      • xlCylinderBarClustered (or 95) to create a clustered cylinder bar chart.
      • xlCylinderBarStacked (or 96) to create a stacked cylinder bar chart.
      • xlCylinderBarStacked100 (or 97) to create a 100% stacked cylinder bar chart.

Macro example to create a clustered or stacked bar chart in a chart sheet

The following macro example creates a stacked bar chart (myChart) in a chart sheet of the workbook containing the macro (ThisWorkbook). For these purposes:

  • The source data (mySourceData) is contained in cells A5 to F10 of the worksheet named “chart sheet bar chart”; and
  • The chart sheet containing the stacked bar chart is located before the first sheet within ThisWorkbook.
Sub createChartSheetStackedBarChart()

    'source: https://powerspreadsheets.com/
    'creates a stacked bar chart in a chart sheet
    'for further information: https://powerspreadsheets.com/vba-create-bar-chart/

    'declare object variables to hold references to source data and created bar chart
    Dim mySourceData As Range
    Dim myChart As Chart

    'identify source data
    Set mySourceData = ThisWorkbook.Worksheets("chart sheet bar chart").Range("A5:F10")

    'add chart sheet containing bar chart
    Set myChart = ThisWorkbook.Charts.Add2(Before:=ThisWorkbook.Sheets(1), NewLayout:=False)

    With myChart

        'set source data for created bar chart
        .SetSourceData Source:=mySourceData

        'set chart type of created bar chart
        .ChartType = xlBarStacked

    End With

End Sub

Effects of executing macro example to create a clustered or stacked bar chart in a chart sheet

The following image illustrates the results of executing the macro example. A stacked bar chart is created on a new chart sheet, which becomes the first sheet of the workbook. The source data for this chart is in a separate worksheet.

Stacked bar chart created in chart sheet with macro

References to VBA Constructs Used in this VBA Tutorial

Use the following links to visit the appropriate webpage in the Microsoft Developer Network:

  1. Identify or activate the workbook and worksheet that contains the source data and/or where the bar chart is to be created:
    • Workbook object.
    • Application.ActiveWorkbook property.
    • Application.ThisWorkbook property.
    • Application.Workbooks property.
    • Worksheet object.
    • Application.ActiveSheet property.
    • Workbook.Worksheets property.
    • Worksheet.Activate method.
  2. Identify or select the cell range containing the source data and/or the cell range where the bar chart is to be created:
    • Range object.
    • Worksheet.Range property.
    • Worksheet.Cells property.
    • Application.Selection property.
    • Range.Cells property.
    • Range.Item property.
    • Range.Offset property.
    • Range.Resize property.
    • Range.Select method.
  3. Work with the Shapes collection representing all Shape objects in a worksheet or the Charts collection representing all Chart objects in a workbook:
    • Shapes object.
    • Worksheet.Shapes property.
    • Charts object.
    • Workbook.Charts property.
  4. Create a bar chart:
    • Shapes.AddChart2 method.
    • Shapes.AddChart method.
    • Charts.Add2 method.
    • Charts.Add method.
  5. Return a Chart object:
    • Chart object.
    • Shape.Chart property.
  6. Set the source data range for a bar chart:
    • Chart.SetSourceData method.
  7. Specify the type of a bar chart:
    • Chart.ChartType property.
    • XlChartType enumeration.
  8. Measure distances, heights or widths in points:
    • Range.Left property.
    • Range.Top property.
    • Range.Width property.
    • Range.Height property.
  9. Work with variables and data types:
    • Dim statement.
    • Set statement.
    • = operator.
    • Boolean data type.
  10. Simplify object references:
    • With… End With statement.

Содержание

  • 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>

Программное создание графика (диаграммы) в 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 из первого примера:

Объект Chart с типом графика по умолчанию

Пример 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 из второго примера:

Объект Chart с двумя линейными графиками (с маркерами)

Пример 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 с круговой диаграммой

Примечание

В примерах использовались следующие методы и свойства объекта Chart:

Компонент Описание
Метод SetSourceData Задает диапазон исходных данных для диаграммы.
Метод Location Перемещает диаграмму в заданное расположение (новый лист, существующий лист, элемент управления).
Свойство ChartType Возвращает или задает тип диаграммы. Смотрите константы.
Свойство ChartStyle Возвращает или задает стиль диаграммы. Значение нужного стиля можно узнать, записав макрос.

Понравилась статья? Поделить с друзьями:
  • Excel vba bad file name or number
  • Excel vba char string
  • Excel vba background color
  • Excel vba change all cells
  • Excel vba autofilter criteria not