在 Word 2007 Service Pack 2 (SP2) 及更高版本中,可以在 Word 中使用 VBA 对象模型以编程方式访问和处理图表。 Word 中的图表对象是通过与 Excel 所用相同的共享 Office 绘图层实现来绘制的,所以如果您熟悉 Excel 中的图表对象模型,则只需将用于处理图表的 Excel VBA 代码迁移到 Word VBA 代码中。
Chart 对象用法
在 Word 中,图表由 Chart 对象来表示。 Chart 对象包含在 InlineShape 或 Shape 中。 使用 Document 对象的 InlineShapes 集合或 Shapes 集合添加新图表或访问现有图表。 使用这两个集合的 AddChart 方法可添加新图表,该方法可指定文档内的图表类型和位置。
使用 HasChart 属性可确定 InlineShape 对象或 Shape 对象是否包含图表。 如果 HasChart 返回 True,则可以使用 Chart 属性获取对代表图表的 Chart 对象的引用。 此时,实现实际上与 Excel 的实现相同,并且在大多数情况下,VBA 代码可以在这两个程序之间转用。
例如,下面的 VBA 代码示例向 Excel 活动工作表中添加一个新的二维堆积柱形图,并将图表的源数据设置为 Sheet1 工作表中的区域 A1:C3。
Sub AddChart_Excel()
Dim objShape As Shape
' Create a chart and return a Shape object reference.
' The Shape object reference contains the chart.
Set objShape = ActiveSheet.Shapes.AddChart(XlChartType.xlColumnStacked100)
' Ensure the Shape object contains a chart. If so,
' set the source data for the chart to the range A1:C3.
If objShape.HasChart Then
objShape.Chart.SetSourceData Source:=Range("'Sheet1'!$A$1:$C$3")
End If
End Sub
作为比较,下面的 VBA 代码示例向活动文档中添加一个新的二维堆积柱形图,并将图表的源数据设置为与该图表相关联的图表数据中的范围 A1:C3。
Sub AddChart_Word()
Dim objShape As InlineShape
' Create a chart and return a Shape object reference.
' The Shape object reference contains the chart.
Set objShape = ActiveDocument.InlineShapes.AddChart(XlChartType.xlColumnStacked100)
' Ensure the Shape object contains a chart. If so,
' set the source data for the chart to the range A1:C3.
If objShape.HasChart Then
objShape.Chart.SetSourceData Source:="'Sheet1'!$A$1:$C$3"
End If
End Sub
Word 中 Chart 对象与 Excel 中 ChartObject 对象的重要区别
即使大多数情况下您在 Excel 和 Word 中处理图表的方式几乎相同,但是了解这两种实现在哪些重要方面有所不同还是有帮助的:
在 Word 中以编程方式创建或处理 ChartData 对象需要运行 Excel。
将不执行用于处理图表工作表的图表属性和方法。 图表工作表的概念是特定于 Excel 的。 图表工作表不用于 Word,所以已经对这些应用程序禁用用于引用或处理工作表图表的方法和属性。
在 Excel 中通常采用 Range 对象引用的属性和方法现在采用 Word 中的范围地址。 Word 中的 Range 对象与 Excel 中的 Range 对象不同。 为防止混淆,Word 中的图表对象模型接受区域地址字符串,如“='Sheet1'!$A$1:$D$5”,这些属性和方法 (如 Chart 对象的 SetSourceData 方法,) 接受 Excel 中的 Range 对象。
已将新对象 ChartData 添加到 Word 的 VBA 对象模型中,以提供对图表的基础链接或嵌入数据的访问权限。 每个图表都有用于在 Word 中绘制图表的数据(与之关联)。 图表数据可以从外部 Excel 工作簿链接,也可以嵌入为图表本身的一部分。 ChartData 对象封装对 Word 中给定图表数据的访问。 例如,下面的 VBA 代码示例显示 Word 中活动文档包含的每个图表的图表数据,然后将其最小化。
Sub ShowWorkbook_Word()
Dim objShape As InlineShape
' Iterates each inline shape in the active document.
' If the inline shape contains a chart, then display the
' data associated with that chart and minimize the application
' used to display the data.
For Each objShape In ActiveDocument.InlineShapes
If objShape.HasChart Then
' Activate the topmost window of the application used to
' display the data for the chart.
objShape.Chart.ChartData.Activate
' Minimize the application used to display the data for
' the chart.
objShape.Chart.ChartData.Workbook.Application.WindowState = -4140
End If
Next
End Sub
支持和反馈
有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。