A Class Module to Manipulate a Chart SERIESExcel's object model has a serious flaw: There is no direct way to to use VBA to determine the ranges used in a chart. This tip contains a useful class module that can simplify the task of manipulating chart's using VBA. Background InformationThe Series object is contained in a Chart object. The SeriesCollection is a collection of Series objects for a particular Chart object. If a chart plots two data series it will have two Series objects. You can refer to a particular Series object by its index number. The expression below, for example, creates an object variable that represents the first Series object in the active chart: Set MySeries = ActiveChart.SeriesCollection(1) A Series object has many properties, but I'll list three that seem relevant to this discussion:
If your VBA code needs to determine the data range used by a particular chart series, it's obvious that the Values property of the Series object is just the ticket. And, you can use the XValues property to get the range that contains the x values (or category labels). In theory, that certainly seems correct -- but in practice, it doesn't work. You'll find that he XValues and Values properties return a variant array. Unfortunately, there is no direct way to get a Range object for a Series object. Note: When you set the Values property for a Series object, you can specify a Range object or an array. But when you read this property, it is always an array. Go figure. About a Chart's SERIES formulaEvery data series in a chart has a SERIES formula that determines the data used in the series. Here's an example of a SERIES formula for a chart series: =SERIES(Sheet1!$B$1,Sheet1!$A$2:$A$13,Sheet1!$B$2:$B$13,1) A SERIES formula is comprised of four arguments:
The ChartSeries calls module, described below, essentially parses and analyzes a chart's SERIES formula. The ChartSeries Class ModuleI created a class module named ChartSeries. When this class module is included in a workbook, your VBA code can create a new "ChartSeries" object and manipulate the following properties of this object:
Example UsageThe simple procedure below demonstrate how to use the ChartSeries class. It starts by creating a new object called ChartSeries. It sets the Chart property to an embedded chart, and sets the ChartSeries property to 1. It then uses the XValuesType property to determine the "type" of the XValues in the chart. If the chart uses a range, it displays the address of the range. If the chart uses something other than a range (that is, a literal array), it displays the array. Sub ExampleUsage()
Dim MySeries As New ChartSeries
With MySeries
Chart = Sheets(1).ChartObjects(1).Chart
ChartSeries = 1
If .XValuesType = "Range" Then
MsgBox .XValues.Address
Else
MsgBox .XValues
End If
End With
End Sub
View or DownloadClick the links below to view the class module code or download an example workbook.
|