Excel图表制作,一直是个难点,由于其类型多,格式也复杂,涉及到的图形也比较多,所以在使用过程当中,会发现有点不知所措。
Chart对象
本节简单介绍一下,使用VBA代码在数据表中的系列值如何设置和返回。
首先还是要获取一个Chart对象,上节我们介绍过,Chart对象就是代表一个图表。
一个图表里面包含了很多图片、文本,下面就对这些图片、文本进行设置做一个梳理。
如下图所示:提取出图表中的年龄和姓名生成一表。
代码
可以重点看一下代码,对照代码进行理解:
Option Explicit
Private Sub GetSeries()
Dim xChart As Object
Set xChart = ThisWorkbook.Charts(1) '返回Chart图表工作表
Dim i As Integer, n As Integer
n = xChart.SeriesCollection.Count '返回系列总数
For i = 1 To n
Range("B6").Offset(i, 0) = xChart.SeriesCollection(i).Name
Next i
Dim xChartObject As Object, xSeries As Object
n = xChart.SeriesCollection.Count
If n >= 1 Then
For i = 1 To n
Set xSeries = xChart.SeriesCollection(i)
Range("B6").Offset(i - 1, 1).Value = xSeries.Name
Next i
End If
xSeries.Select
Dim x As Variant, xArr()
xArr = xSeries.XValues '返回x轴值数组
i = 1
For Each x In xArr
Range("B6").Offset(i, 0).Value = xArr(i)
i = i + 1
Next x
xArr = xSeries.Values '返回系列值数组
i = 1
For Each x In xArr
Range("B6").Offset(i, 1).Value = xArr(i)
i = i + 1
Next x
End Sub
关键代码:
- Set xChart = ThisWorkbook.Charts(1) '返回Chart图表工作表
- Set xSeries = xChart.SeriesCollection(1)'返回第一个系列对象
- xArr = xSeries.XValues '返回x轴值数组
- xArr = xSeries.Values'返回系列值数组
- xSeries.Values = Array(222, 221, 1111)'设置系列值
- xSeries.XValues = Array("姓名一", "姓名二", "姓名三") '设置x轴系列值
Series对象方法和属性
方法 | 属性 |
ApplyDataLabels | Application |
ClearFormats | ApplyPictToEnd |
Copy | ApplyPictToFront |
DataLabels | ApplyPictToSides |
Delete | AxisGroup |
ErrorBar | BarShape |
Paste | BubbleSizes |
Points | ChartType |
Select | Creator |
Trendlines | ErrorBars |
Explosion | |
Format | |
Formula | |
FormulaLocal | |
FormulaR1C1 | |
FormulaR1C1Local | |
GeoMappingLevel | |
GeoProjectionType | |
Has3DEffect | |
HasDataLabels | |
HasErrorBars | |
HasLeaderLines | |
InvertColor | |
InvertColorIndex | |
InvertIfNegative | |
IsFiltered | |
LeaderLines | |
MarkerBackgroundColor | |
MarkerBackgroundColorIndex | |
MarkerForegroundColor | |
MarkerForegroundColorIndex | |
MarkerSize | |
MarkerStyle | |
Name | |
Parent | |
ParentDataLabelOption | |
PictureType | |
PictureUnit2 | |
PlotColorIndex | |
PlotOrder | |
QuartileCalculationInclusiveMedian | |
RegionLabelOptions | |
Shadow | |
Smooth | |
Type | |
Values | |
XValues |
很显然,用到了不止一个对象,有Chart、Series和SeriesCollection,三个对象。
这三个对象分别有许多方法和属性,而这里用到了Series的xValues和Values两个。
其它方法属性,下次再做详细介绍。
关键是如何获取对象,并对对象的哪些属性进行修改,这样再编程序的时候就可以方便地解决我们的需求了。
欢迎关注、收藏
---END---
