5、AddDataSeries函数
[入库:2005年8月18日] [更新:2007年3月24日]
该函数加入来自记录集指定列的一组数据。
public sub adddataseries(byval ors as adodb.recordset, _
byval strvaluecol as string, byval strseriesname as string, _
byval flgshowdatalabels as boolean, _
byval flgshaded as boolean)
dim icount as integer
dim irow, icol as integer
dim nmaxrows as integer
'--- 检查参数是否合法
if (isnull(ors) or isnull(strvaluecol)) then
err.raise number:=1001 + vbobjecterror, description:="invalid recordset or column name"
exit sub
end if
on error goto herror
'--- 数据系列中最大数据个数
nmaxrows = 25
'--- 设置初始值和位置
ors.movefirst
irow = 0: icol = oexcelchart.seriescollection.count + 2
'--- 循环,将记录集数据写入工作表列
while (not ors.eof and irow < nmaxrows)
irow = irow + 1
'--- 设置一个单元的值
oexcelsheet.cells(irow, icol) = cdec(ors(strvaluecol).value)
'--- 下一行
ors.movenext
wend
'--- 检查是否确实从记录集读入了数据
if (irow > 0) then
'--- 将新的数据系列加入seriescollection
with oexcelchart.seriescollection.newseries
'--- 将数据工作表中的数据设置为图表数据系列
.values = oexcelsheet.range(oexcelsheet.cells(1, icol), _
oexcelsheet.cells(irow, icol))
'--- 设置数据系列名字
if (not isnull(strseriesname)) then .name = strseriesname
'--- 设置边框风格
.border.weight = xlthin
.border.linestyle = xlautomatic
'--- 如已经指定则设置阴影效果
if (flgshaded = true) then .fill.onecolorgradient style:=1, _
variant:=1, degree:=0.231372549019608
'--- 设置数据标签是否可见
if (flgshowdatalabels) then .applydatalabels type:=2, _
autotext:=true, legendkey:=false
end with
'--- 设置那些只有在加入了数据之后才可以设置的属性
if (oexcelchart.seriescollection.count = 1) then setchartwithdataprops
end if
exit sub
herror:
app.logevent err.description, vblogeventtypeerror
err.raise err.number, err.source, err.description
end sub
|

【图3】
上图所显示的是数据工作表及其对应的图表工作表。
adddataseries()函数担负着大部分与excel接口的工作。传递给adddataseries()函数的数据是记录集形式,而excel应用中图表对象接受的是range形式的数据。range对象代表要求绘制图表的一个单元格或一组单元格。这里函数用到了excel对象模型中的另外一个对象,即chart对象中包含的seriescollection集合对象。所有以记录集形式提供的数据最终被存储到series对象,series对象是seriescollection集合对象的元素。程序中我们特别将数据系列中数据的最大个数设置成了25,当然,这最终决定于开发者。
数据分两个步骤传递到chart对象。第一步是循环遍历记录集,收集excel工作表内单个列的各行数据,例如b1到b5。第一列即a列留给x-轴上的标签,第一个数据系列写入第二列,第二个数据系列写入第三列,依此类推。
数据从记录集转到工作表之后就可以把它们视为range对象里面的数据,接下来是在chart对象的seriescollection集合里添加数据系列,利用excelsheet对象的range()方法传送数据。
接下来的几行代码完成一些装饰图表的任务,比如设置数据系列的名字(作为图表中的图例显示),如果已经指定的话则还要设置填充效果。这里用到了另外一个功能强大的对象fill,fill对象用来控制图表的外观以及赋予应用它的对象某种特殊效果。
函数的最后几行代码里调用了setchartwithdataprops()方法。如前所述,图表的某些属性只有在已经将数据加入到图表之后才能设置,因此程序首先检查当前的数据是否属于第一个数据系列然后调用setchartwithdataprops方法。到这里为止,图表绘制已经完成,接下来就可以将它导出为gif文件。
最后三行代码用来控制错误。程序利用visual basic的app对象记录错误,然后使用err对象的raise()方法提醒当前对象的容器注意这个运行时错误。
本文关键:5、AddDataSeries函数
本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)