Download presentation
Presentation is loading. Please wait.
Published byLogan Curtis Modified over 8 years ago
1
Working with charts 1126 1
2
Excel charts An Excel chart is simply packed with objects, each of which has its own properties and methods. Because of this, manipulating charts with Visual Basic for Applications (VBA) can be a bit of a challenge. The secret, as you’ll see, is a good understanding of the object hierarchy for charts. 2
3
Chart locations In Excel, a chart can be located in either of two places in a workbook: As an embedded object on a worksheet: A worksheet can contain any number of embedded charts. In a separate chart sheet: A chart sheet normally holds a single chart. Most users create charts manually by using the commands in the Insert->Charts group. But you can also create charts by using VBA. And, of course, you can use VBA to modify existing charts. 3
4
A key concept when working with charts is the active chart — that is, the chart that’s currently selected. When the user clicks an embedded chart or activates a chart sheet, a Chart object is activated. In VBA, the ActiveChart property returns the activated Chart object (if any). You can write code to work with this Chart object, much like you can write code to work with the Workbook object returned by the ActiveWorkbook property. Here’s an example: If a chart is activated, the following tatement will display the Name property for the Chart object: MsgBox ActiveChart.Name If a chart isn’t activated, the preceding statement generates an error. 4
5
The macro recorder and charts If you’ve read other chapters in the book, you know that I often recommend using the macro recorder to learn about objects, properties, and methods. As always, recorded macros are best viewed as a learning tool. The recorded code will almost always steer you to the relevant objects, properties, and methods. 5
6
The Chart object model When you first start exploring the object model for a Chart object, you’ll probably be confused — which isn’t surprising because the object model is confusing. It’s also deep. For example, assume that you want to change the title displayed in an embedded chart. The top-level object, of course, is the Application object (Excel). The Application object contains a Workbook object, and the Workbook object contains a Worksheet object. The Worksheet object contains a ChartObject object, which contains a Chart object. The Chart object has a ChartTitle object, and the ChartTitle object has a Text property that stores the text displayed as the chart’s title. 6
7
The Chart object model Here’s another way to look at this hierarchy for an embedded chart: Application Workbook Worksheet ChartObject Chart ChartTitle 7
8
The Chart object model Here’s another way to look at this hierarchy for an embedded chart: Application Workbook Worksheet ChartObject Chart ChartTitle 8
9
The Chart object model Your VBA code must, of course, follow this object model precisely. For example, to set a chart’s title to YTD Sales, you can write a VBA instruction like this: Worksheets(1).ChartObjects(1).Chart.ChartTitle.Text= "YTD Sales” This statement assumes that the active workbook is the Workbook object. The statement works with the first object in the ChartOBjects collection on the first worksheet. The Chart property returns the actual Chart object and the ChartTitle property returns the ChartTitle object. Note that preceding statement will fail if the chart does not have a title. 9
10
The Chart object model To add a default title to the chart (which displays the text Chart Title), use this statement: Worksheets("Sheet1").ChartObjects(1).Chart.HasTitle = True For a chart sheet, the object hierarchy is a bit different because it doesn’t involve the Worksheet object or the ChartObject object. For example, here’s the hierarchy for the ChartTitle object for a chart in a chart sheet: Application Workbook Chart ChartTitle You can use this VBA statement to set the chart title in a chart sheet to YTD Sales: Sheets("Chart1").ChartTitle.Text = "YTD Sales" 10
11
The Chart object model A chart sheet is essentially a Chart object, and it has no containing ChartObject object. Put another way, the parent object for an embedded chart is a ChartObject object, and the parent object for a chart on a separate chart sheet is a Workbook object. Both of the following statements will display a message box that displays the word Chart: MsgBox TypeName(Sheets("Sheet1).ChartObjects (1).Chart) Msgbox TypeName(Sheets("Chart1")) 11
12
The Chart object model When you create a new embedded chart, you're adding to the ChartObjects collection and the Shapes collection contained in a particular worksheet. (There is no Charts collection for a worksheet.) When you create a new chart sheet, you're adding to the Charts collection and the Sheets collection for a particular workbook. 12
13
Creating an Embedded Chart A ChartObject is a special type of Shape object. Therefore, it’s a member of the Shapes collection. To create a new chart, use the AddChart2 method of the Shapes collection. The following statement creates an empty embedded chart with all default settings: ActiveSheet.Shapes.AddChart2 13
14
Creating an Embedded Chart The AddChart2 method can use seven arguments (all are optional): Style: A numeric code that specifies the style (or overall look) of the chart. xlChartType: The type of chart. If omitted, the default chart type is used. Constants for all the chart types are provided (for example, xlArea and xlColumnClustered). Left: The left position of the chart, in points. If omitted, Excel centers the chart horizontally. Top: The top position of the chart, in points. If omitted, Excel centers the chart vertically. Width: The width of the chart, in points. If omitted, Excel uses 354. Height: The height of the chart, in points. If omitted, Excel uses 210. NewLayout: A numeric code that specifies the layout of the chart. 14
15
Examples of chart styles (numbers) 15
16
Examples of Chart Styles XlMarkerStyle can be one of these XlMarkerStyle constants. xlMarkerStyleAutomatic. Automatic markers xlMarkerStyleCircle. Circular markers xlMarkerStyleDash. Long bar markers xlMarkerStyleDiamond. Diamond-shaped markers xlMarkerStyleDot. Short bar markers xlMarkerStyleNone. No markers xlMarkerStylePicture. Picture markers xlMarkerStylePlus. Square markers with a plus sign xlMarkerStyleSquare. Square markers xlMarkerStyleStar. Square markers with an asterisk xlMarkerStyleTriangle. Triangular markers xlMarkerStyleX. Square markers with an X 16
17
Chart types ColumnClustered Column xlColumnClustered 3D Clustered Column xl3DColumnClustered Stacked Column xlColumnStacked 3D Stacked Column xl3DColumnStacked 100% Stacked Column xlColumnStackedlOO 3D 100% Stacked Column xl3DColumnStackedl00 3D Column xl3DColumn BarClustered Bar xlBarClustered 3D Clustered Bar xl3DBarClustered Stacked Bar xlBarStacked 3D Stacked Bar xl3DBarStacked 100% Stacked Bar xlBarStackedlOO 3D 100% Stacked Bar xl3DBarStackedl00 17
18
Chart types Line xlLine Line with Markers xlLineMarkers Stacked Line xlLineStacked Stacked Line with Markers xlLineMarkersStacked 100% Stacked Line xlLineStackedlOO 100% Stacked Line with Markers xlLineMarkersStackedlOO 3D Line xl3DLine Pie xlPie Exploded Pie xlPieExploded 3D Pie xl3DPie Exploded 3D Pie xl3DPieExploded Pie of Pie xlPieOfPie Bar of Pie xlBarOfPie 18
19
Chart types XY (Scatter)Scatter xlXYScatter Scatter with Smoothed Lines xlXYScatterSmooth Scatter with Smoothed Lines and No Data Markers xlXYScatterSmoothNoMark ers Scatter with Lines xlXYScatterLines Scatter with Lines and No Data Markers xlXYScatterLinesNoMarkers Bubble xlBubble Bubble with 3D effects xlBubble3DEffeet Area xlArea 3D Area xl3DArea Stacked Area xlAreaStacked 3D Stacked Area xl3DAreaStacked 100% Stacked Area xlAreaStackedlOO 3D 100% Stacked Area xl3DAreaStackedl00 19
20
Chart types Doughnut xlDoughnut Exploded Doughnut xlDoughnutExploded Radar xlRadar Radar with Data Markers xlRadarMarkers Filled Radar xlRadarFilled Surface 3D Surface xlSurface Surface (Top View) xlSurfaceTopView 3D Surface (wireframe) xlSurfaceWireframe Surface (Top View wireframe) ISurfaceTopViewWireframe Stock Quotes High-Low-Close xlStockHLC Volume-High-Low-Close xlstockVHLC Open-High-Low-Close xlStockOHLC Volume-Open-High- Low-Close xlStockVOHLC 20
21
Chart types Cylinder Clustered Cylinder Column xlCylinderColClustered Clustered Cylinder Bar xlCylinderBarClustered Stacked Cylinder Column xlCylinderColStacked Stacked Cylinder Bar xlCylinderBarStacked 100% stacked Cylinder Column xlCylinderColstackedl00 100% stacked Cylinder Bar xlCylinderBarStackedl00 3D Cylinder Column xlCylinderCol Cone Clustered Cone Column xlConeColClustered Clustered Cone Bar xlConeBarClustered Stacked Cone Column xlConeColStacked Stacked Cone Bar xlConeBarStacked 100% Stacked Cone Column xlConeColStackedlOO 100% Stacked Cone Bar xlConeBarStackedlOO 3D Cone Column xlConeCol 21
22
Chart types Pyramid Clustered Pyramid Column xlPyramidColClustered Clustered Pyramid Bar xlPyramidBarClustered Stacked Pyramid Column xlPyramidColStacked Stacked Pyramid Bar xlPyramidBarStacked 100% Stacked Pyramid Column xlPyramidColStackedlOO 100% Stacked Pyramid Bar xlPyramidBarStackedlOO 22
23
Creating charts with VBA Here's a statement that creates a clustered column chart, using Style 2 and Layout 5, positioned 50 pixels from the left, 60 pixels from the top, 300 pixels wide, and 200 pixels high: ActiveSheet.Shapes.AddChart2 201, xlColumnClustered, 50, 60, 300, 200, 5 In many cases, you may find it efficient to create an object variable when the chart is created. The following procedure creates a line chart that you can reference in code by using the MyChart object variable. Note that the AddChart2 method specifies only the first two arguments. The other five arguments use default values. Sub CreateChart() Dim MyChart As Chart Set MyChart = ActiveSheet.Shapes.AddChart2(212,xlLineMarkers).Chart End Sub 23
24
Creating charts with VBA A chart without data isn't useful. You can specify data for a chart in two ways: Select cells before your code creates the chart Use the SetSourceData method of the Chart object after the chart is created Here's a simple procedure that selects a range of data and then creates a chart: Sub CreateChart2() Range("A1:B6").Select ActiveSheet.Shapes.AddChart2 201, xlColumnClustered End Sub 24
25
Creating charts with VBA The procedure that follows demonstrates the SetSourceData method. This procedure uses two object variables: DataRange (for the Range object that holds the data) and MyChart (for the Chart object). The MyChart object variable is created at the same time the chart is created. Sub CreateChart3() Dim MyChart As Chart Dim DataRange As Range Set DataRange = ActiveSheet.Range("A1:B6") Set MyChart = ActiveSheet.Shapes.AddChart2.Chart MyChart.SetSourceData Source:=DataRange End Sub 25
26
26
27
Creating a Chart on a Chart Sheet The preceding section describes the basic procedures for creating an embedded chart. To create a chart directly on a chart sheet, use the Add2 method of the Charts collection. The Add2 method of the Charts collection uses several optional arguments, but these arguments specify the position of the chart sheet — not chart-related information. The example that follows creates a chart on a chart sheet and specifies the data range and chart type: Sub CreateChartSheet() Dim MyChart As Chart Dim DataRange As Range Set DataRange = ActiveSheet.Range("A1:C7") Set MyChart = Charts.Add2 MyChart.SetSourceData Source:=DataRange ActiveChart.ChartType = xlColumnClustered End Sub 27
28
28
29
Modifying Charts Enhancements in Excel 2013 make it easier than ever for end users to create and modify charts. For example, when a chart is activated, Excel displays three icons on the right side of the chart: Chart Elements (used to add or remove elements from the chart), Style & Color (used to select a chart style or change the color palette), and Chart Filters (used to hide series or data points). 29
30
Modifying Charts Your VBA code can perform all the actions available from the new chart controls. For example, if you turn on the macro recorder while you add or remove elements from a chart, you'll see that the relevant method is SetElement (a method of the Chart object). This method takes one argument, and predefined constants are available. For example, to add primary horizontal gridlines to the active chart, use this statement: ActiveChart.SetElement msoElementPrimaryValueGridLinesMaj Or to remove the primary horizontal gridlines, use this statement: ActiveChart.SetElement msoElementPrimaryValueGridLinesNone 30
31
Modifying Charts Use the ChartStyle property to change the chart to a predefined style. The styles are numbers, and no descriptive constants are available. For example, this statement changes the style of the active chart to Style 215: ActiveChart.ChartStyle = 215 Valid values for the ChartStyle property are 1-48 and 201-248. The latter group consists of new styles introduced in Excel 2013. Also, keep in mind that the actual appearance of the styles isn’t consistent across Excel versions. For example, applying style 48 looks different in Excel 2010. To change the color scheme used by a chart, set its ChartColor property to a value between 1 and 26. For example: ActiveChart.ChartColor = 12 The ChartColor property is new to Excel 2013. 31
32
Modifying Charts When you combine the 96 ChartStyle values with the 26 ChartColor options, you have 2,496 combinations — enough to satisfy just about anyone. And if those pre-built choices aren’t enough, you have control over every element in a chart. For example, the following code changes the fill color for one point in a chart series: With ActiveChart.FullSeriesCollection(1).Poin ts(2).Format.Fill.Visible = msoTrue.ForeColor.ObjectThemeColor = msoThemeColorAccent2.ForeColor.TintAndShade = 0.4.ForeColor.Brightness = -0.25.Solid End With 32
33
Using VBA to Activate a Chart When a user clicks any area of an embedded chart, the chart is activated. Your VBA code can activate an embedded chart with the Activate method. Here’s a VBA statement that’s the equivalent of clicking an embedded chart to activate it: ActiveSheet.ChartObjects("Chart 1").Activate If the chart is on a chart sheet, use a statement like this: Sheets("Chart1").Activate Alternatively, you can activate a chart by selecting its containing Shape: ActiveSheet.Shapes("Chart 1").Select 33
34
Using VBA to Activate a Chart When a chart is activated, you can refer to it in your code by using the ActiveChart property (which returns a Chart object). For example, the following instruction displays the name of the active chart. If no active chart exists, the statement generates an error: MsgBox ActiveChart.Name 34
35
Using VBA to Activate a Chart To modify a chart with VBA, it’s not necessary to activate it. The two procedures that follow have exactly the same effect. That is, they change the embedded chart named Chart 1 to an area chart. The first procedure activates the chart before performing the manipulations; the second one doesn’t: Sub ModifyChart1() ActiveSheet.ChartObjects("Chart1").Activate ActiveChart.ChartType =xlArea End Sub Sub ModifyChart2() ActiveSheet.ChartObjects("Chart 1").Chart.ChartType = xlArea End Sub 35
36
Moving a Chart A chart embedded on a worksheet can be converted to a chart sheet. To do so manually, just activate the embedded chart and choose Chart Tools^Design^Location^Move Chart. In the Move Chart dialog box, select the New Sheet option and specify a name. You can also convert an embedded chart to a chart sheet by using VBA. Here’s an example that converts the first ChartObject on a worksheet named Sheetl to a chart sheet named MyChart: Sub MoveChart1() Sheets("Sheet1").ChartObjects(1).Chart.Location xlLocationAsNewSheet, "MyChart" End Sub 36
37
Moving a Chart The following example does just the opposite of the preceding procedure: It converts the chart on a chart sheet named MyChart to an embedded chart on the worksheet named Sheet1. Sub MoveChart2() Charts("MyChart").Location xlLocationAsObject, "Sheet1" End Sub 37
38
Using VBA to Deactivate a Chart You can use the Activate method to activate a chart, but how do you deactivate (that is, deselect) a chart? As far as I can tell, the only way to deactivate a chart by using VBA is to select something other than the chart. For an embedded chart, you can use the RangeSelection property of the ActiveWindow object to deactivate the chart and select the range that was selected before the chart was activated:ActiveWindow.RangeSelection.Select To deactivate a chart on a chart sheet, just activate a different sheet. 38
39
Chart names can be confusing… Every ChartObject object has a name, and every Chart object contained in a ChartObject has a name. That statement seems straightforward, but chart names can be confusing. Create a new chart on Sheet! and activate it Then activate the VBA Immediate window and type a few commands: ? ActiveSheet.Shapes(1).Name (what you see in return) Chart 1 ? ActiveSheet.ChartObjects(1).Name Chart 1 ? ActiveChart.Name Sheet1 Chart 1 ? Activesheet.ChartObjects(1).Chart.Name Sheet1 Chart 1 39
40
Chart names can be confusing… If you change the name of the worksheet the name of the chart also changes to include the new sheet name. You can also use the Name box (to the left of the Formula bar) to change a Chart object's name, and also change the name using VBA: Activesheet.ChartObjects(1).Name = "New Name" However, you can't change the name of a Chart object contained in a ChartObject This statement generates an inexplicable "out of memory" error: Activesheet.ChartObjects(1).Chart.Name = "New Name" Oddly, Excel allows you to use the name of an existing ChartObject. In other words, you could have a dozen embedded charts on a worksheet, and every one of them can be named Chart 1. If you make a copy of an embedded chart, the new chart has the same name as the source chart, 40
41
Determining Whether a Chart Is Activated A common type of macro performs some manipulations on the active chart (the chart selected by a user). For example, a macro might change the chart’s type, apply a style, add data labels, or export the chart to a graphics file. The question is how can your VBA code determine whether the user has actually selected a chart? By selecting a chart, I mean either activating a chart sheet or activating an embedded chart by clicking it. Your first inclination might be to check the TypeName property of the Selection, as in this expression: TypeName(Selection) = "Chart" In fact, this expression never evaluates to True. When a chart is activated, the actual selection will be an object within the Chart object. For example, the selection might be a Series object, a ChartTitle object, a Legend object, or a PlotArea object. The solution is to determine whether ActiveChart is Nothing. If so, a chart isn’t active. 41
42
Determining Whether a Chart Is Activated The following code checks to ensure that a chart is active. If not, the user sees a message, and the procedure ends: If ActiveChart Is Nothing Then MsgBox "Select a chart." Exit Sub Else 'other code goes here End If You may find it convenient to use a VBA function procedure to determine whether a chart is activated. The ChartlsSelected function, which follows, returns True if a chart sheet is active or if an embedded chart is activated, but returns False if a chart isn’t activated: Private Function ChartIsActivated() As Boolean ChartlsActivated = Not ActiveChart Is Nothing End Function 42
43
Deleting from the ChartObjects or Charts Collection To delete a chart on a worksheet, you must know the name or index of the ChartObject or the Shape object. This statement deletes the ChartObject named Chart 1 on the active worksheet: ActiveSheet.ChartObjects("Chart 1").Delete Keep in mind that multiple ChartObjects can have the same name. If that’s the case, you can delete a chart by using its index number: ActiveSheet.ChartObjects(1).Delete To delete all ChartObject objects on a worksheet, use the Delete method of the ChartObjects collection: ActiveSheet.ChartObjects.Delete 43
44
Deleting from the ChartObjects or Charts Collection You can also delete embedded charts by accessing the Shapes collection. The following statement deletes the shape named Chart 1 on the active worksheet: ActiveSheet.Shapes("Chart 1").Delete This code deletes all embedded charts (and all other shapes) on the active sheet: Dim shp as Shape For Each shp In ActiveSheet.Shapes shp.Delete Next shp 44
45
Deleting from the ChartObjects or Charts Collection To delete a single chart sheet, you must know the chart sheet’s name or index. The following statement deletes the chart sheet named Chart 1: Charts ("Chart1").Delete To delete all chart sheets in the active workbook, use the following statement: ActiveWorkbook.Charts.Delete Deleting sheets causes Excel to display a warning. The user must reply to this prompt for the macro to continue (or…): Application.DisplayAlerts = False 45
46
Looping through All Charts In some cases, you may need to perform an operation on all charts. The following example applies changes to every embedded chart on the active worksheet. The procedure uses a loop to cycle through each object in the ChartObjects collection and then accesses the Chart object in each and changes several properties. 46
47
Sub FormatAllCharts() Dim ChtObj As ChartObject For Each ChtObj In ActiveSheet.ChartObjects With ChtObj.Chart.ChartType = xlLineMarkers.ApplyLayout 3.ChartStyle = 12. ClearToMatchStyle. SetElement msoElementChartTitleAboveChart. SetElement msoElementLegendNone. SetElement msoElementPrimaryValueAxisTitleNone. SetElement msoElementPrimaryCategoryAxisTitleNone.Axes(xlValue).MinimumScale = 0.Axes(xlValue).MaximumScale = 1000 With.Axes(xlValue).MajorGridlines.Format.Lin.ForeColor.Obj ectThemeColor = msoThemeColorBackground1.ForeColor.TintAndShade = 0.ForeColor.Brightness = -0.25.DashStyle = msoLineSysDash.Transparency = 0 End With Next ChtObj End Sub 47
48
Looping through All Charts The following macro performs the same operation as the preceding FormatAllCharts procedure but works on all the chart sheets in the active workbook: 48
49
Sub FormatAllCharts2() Dim cht as Chart For Each cht In ActiveWorkbook.Charts With cht.ChartType = xlLineMarkers.ApplyLayout 3.ChartStyle = 12.ClearToMatchStyle. SetElement msoElementChartTitleAboveChart. SetElement msoElementLegendNone.SetElement msoElementPrimaryValueAxisTitleNone.SetElement msoElementPrimaryCategoryAxisTitleNone.Axes(xlValue).MinimumScale = 0.Axes(xlValue).MaximumScale = 1000 With.Axes(xlValue).MajorGridlines.Format.Line.ForeColor.Obj ectThemeColor = msoThemeColorBackground1.ForeColor.TintAndShade = 0.ForeColor.Brightness = -0.25.DashStyle = msoLineSysDash.Transparency = 0 End With Next cht End Sub 49
50
Sizing and Aligning ChartDbjects A ChartObject object has standard positional (Top and Left) and sizing (Width and Height) properties that you can access with your VBA code. The Excel Ribbon has controls (in the Chart Tools Format Size group) to set the Height and Width, but not the Top and Left. The following example resizes all ChartObject objects on a sheet so that they match the dimensions of the active chart. It also arranges the ChartObject objects into a user-specified number of columns. If no chart is active, the user is prompted to activate a chart that will be used as the basis for sizing the other charts. (we use an InputBox function to get the number of columns. The values for the Left and Top properties are calculated within the loop.) 50
51
Sub SizeAndAlignCharts() Dim W As Long, H As Long Dim TopPosition As Long, LeftPosition As Long Dim ChtObj As ChartObject Dim i As Long, NumCols As Long If ActiveChart Is Nothing Then MsgBox "Select a chart to be used as the base for the sizing" Exit Sub End If 'Get columns On Error Resume Next NumCols = InputBox("How many columns of charts?") If Err.Number <> 0 Then Exit Sub If NumCols < 1 Then Exit Sub On Error GoTo 0 'Get size of active chart W = ActiveChart.Parent.Width H = ActiveChart.Parent.Height 'Change starting positions, if necessary TopPosition = 100 LeftPosition = 20 For i = 1 To ActiveSheet.ChartObjects.Count With ActiveSheet.ChartObjects(i).Width = W.Height = H.Left = LeftPosition + ((i- 1) Mod NumCols) * W.Top = TopPosition + Int((i- 1)/ NumCols) * H End With Next i End Sub 51
52
Creating lots of Charts 1NameDay 1Day 2Day 3Day 4 2Daisy Allen37537072 3Joe Pfliify49566158 4Joe Long44327169 5Stephen Miïcheli49515574 6Thelma Carter32251531 7Susie Fitzgerald4767592 8Gerard Johnson40567536 9Wary Young33343350 10Robert Mcdonaid39577285 11Robert Hall39544945 12Jennifer Head58504345 13Todd FoMer32424042 14Margaret Adams53717372 15William Smith42403637 16Douglas Taylor4946 36 17Evelyn Reyes39364134 18Peter Gonzales34494764 19Victor Klein38433350 20Christophe r Anderson32233430 21Raul Jones31253022 Bernard Jones43465266 23Norma Young53675750 24Francis Valencia49666560 25Shannon Taylor57596779 52
53
53
54
Changing the Data Used in a Chart The examples so far have used the SourceData property to specify the complete data range for a chart. In many cases, you’ll want to adjust the data used by a particular chart series. To do so, access the Values property of the Series object. The Series object also has an XValues property that stores the category axis values. 54
55
Changing chart data based on the active cell Figure on the next slide shows a chart that’s based on the data in the row of the active cell. When the user moves the cell pointer, the chart is updated automatically. This example uses an event handler for the Sheet1 object. The SelectionChange event occurs whenever the user changes the selection by moving the cell pointer. The event-handler procedure for this event (which is located in the code module for the Sheet1 object) is as follows: 55
56
56
57
Changing chart data based on the active cell Private Sub CheckBox1_Click() If CheckBox1 Then Call UpdateChart ActiveCell.Select End If End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) If CheckBox1 Then Call UpdateChart End Sub 57
58
Changing chart data based on the active cell Sub UpdateChart() Dim ChtObj As ChartObject Dim UserRow As Long Set ChtObj = ActiveSheet.ChartObjects(1) UserRow = ActiveCell.Row If UserRow < 4 Or IsEmpty(Cells(UserRow, 1)) Then ChtObj.Visible = False Else ChtObj.Chart.SeriesCollection(1).Values = _ Range(Cells(UserRow, 2), Cells(UserRow, 6)) ChtObj.Chart.ChartTitle.Text = Cells(UserRow, 1).Text ChtObj.Visible = True End If End Sub 58
59
Understanding a chart's SERIES formula The data used in each series in a chart is determined by its SERIES formula. When you select a data series in a chart, the SERIES formula appears in the formula bar. This is net a real formula: In ether words, you can't use it in a cell, and you can't use worksheet functions within the SERIES formula. You can, how ever, edit the arguments in the SERIES formula. A SERIES formula has the following syntax: =SERIES(series_name, category_labels, values, order, sizes) The arguments that you can use in the SERIES formula are: ■ series_name: Optional. A reference to the cell that contains the series name used in the legend. If the chart has only one series, the name argument is used as the title. This argument can also consist of text in quotation marks. If omitted, Excel creates a default series name (f.e. Series1). 59
60
Understanding a chart's SERIES formula ■ category_labels: Optional. A reference to the range that contains the labels for the category axis. If omitted, Excel uses consecutive integers beginning with 1. For XY charts, this argument specifies the X values. The ranges' addresses are separated by a comma and enclosed in parentheses. The argument could also consist of an array of comma-separated values (or text in quotation marks) enclosed in curly brackets. ■ values: Required. A reference to the range that contains the values for the series. For XY charts, this argument specifies the Y values. A noncontiguous range reference is also valid. The ranges' addresses are separated by a comma and enclosed in parentheses. The argument could also consist of an array of comma-separated values enclosed in curly brackets. ■ order: Required. An integer that specifies the plotting order of the series. This argument is relevant only if the chart has more than one series. For example, in a stacked column chart, this parameter determines the stacking order. Using a reference to a cell is not allowed. 60
61
Understanding a chart's SERIES formula ■ sizes: Only for bubble charts. A reference to the range that contains the values for the size of the bubbles in a bubble chart. A noncontiguous range reference is also valid. The ranges' addresses are separated by a comma and enclosed in parentheses. The argument could also consist of an array of values enclosed in curly brackets. Range references in a SERIES formula are always absolute, and they always include the sheet name. For example: =SERIES(Sheet1!$B$1,,Sheet1!$B$2:$B$7,1) A range reference can consist of a noncontiguous range. If so, each range is separated by a comma, and the argument is enclosed in parentheses. In the follow ing SERIES formula, the values range consists of B2:B3 and B5:B7: =SERIES(,,(Sheet1!$B$2:$B$3,Sheet1!$B$5:$B$7),1) You can substitute range names for the range references. If you do so (and the name is a workbook-level name), Excel changes the reference in the SERIES formula to include the workbook. For example: =SERIES(Sheet1!$B$1,,budget.xlsx!CurrentData,1) 61
62
Understanding Chart Events Excel supports several events associated with charts. For example, when a chart is activated, it generates an Activate event. The Calculate event occurs after the chart receives new or changed data. You can, of course, write VBA code that gets executed when a particular event occurs. 62
63
Understanding Chart Events EventAction That Triggers the Event ActivateA chart sheet or embedded chart is activated. BefareDouble Click An embedded chart is double-clicked. This event occurs befare the default double-click action. BefareR'qhtCli ck An embedded chart is riqht-clicked. The event occurs befare the default riqht-click action. CalculateNew or changed data is plotted on a chart. DeactivateA chart is deactivated. MauseDawnA mouse button is pressed while the pointer is over a chart. MouseMoveThe position of the mouse pointer changes over a chart. MauseUpA mouse button is released while the pointer is over a chart. ResizeA chart is resized. SelectA chart element is selected. SeriesChanqeThe value of a chart data point is changed. 63
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.