在Word和PowerPoint中的图表对象模型

1 颗星2 颗星3 颗星4 颗星5 颗星 (目前还没有人投票)
Loading ... Loading ...

作为Office 2007发布版的一部分,我们对Office中的图表作了较大的修改,然而并没有为Word和PowerPoint提供对象模型。响应用户的反馈,在Office 2007 SP2和Office 2010中,我们公布了Word和PowerPoint中统一的/一致的图表对象模型,因此,你可以为任何利用了新的图表功能的应用程序编写解决方案。图表通过相同的共享的Office绘图层来绘制,因此如果你熟悉Excel 2007中的对象模型,那么可以容易地在Word和PowerPoint中创建相似的解决方案。
公司经常需要基于客户端指定的数据在文档或演示文档中创建图表。在许多情况下,这些图表有标准格式、大小和位置,使之首选自动化操作完成。这个对象模型能够被用作解决方案的一部分,以自动生成图表,从而节省时间。
下面看一个示例:如何基于已经获得的数据在PowerPoint中创建图表并应用标准的格式。

Sub CreateChart()
    Dim myChart As Chart
    Dim gChartData As ChartData
    Dim gWorkBook As Excel.Workbook
    Dim gWorkSheet As Excel.Worksheet
 
    Set myChart = ActivePresentation.Slides(1).Shapes.AddChart.Chart '创建/设置图表
    Set gChartData = ActivePresentation.Slides(1).Shapes(1).Chart.ChartData '设置图表数据
    Set gWorkBook = gChartData.Workbook '设置工作簿对象引用
    Set gWorkSheet = gWorkBook.Worksheets(1) '设置工作表对象引用
 
    gWorkSheet.ListObjects("Table1").Resize gWorkSheet.Range("A1:B5") '添加数据
    gWorkSheet.Range("Table1[[#Headers],[Series 1]]").Value = "Sales"
    gWorkSheet.Range("a2").Value = "Bikes"
    gWorkSheet.Range("a3").Value = "Accessories"
    gWorkSheet.Range("a4").Value = "Repairs"
    gWorkSheet.Range("a5").Value = "Clothing"
    gWorkSheet.Range("b2").Value = "1000"
    gWorkSheet.Range("b3").Value = "2500"
    gWorkSheet.Range("b4").Value = "4000"
    gWorkSheet.Range("b5").Value = "3000"
 
    With myChart '应用样式
        .ChartStyle = 4
        .ApplyLayout 4
        .ClearToMatchStyle
    End With
 
    myChart.HasTitle = True '添加标题
 
    With myChart.ChartTitle '格式化标题
        .Characters.Font.Size = 18
        .Text = "2007 Sales"
    End With
 
    With myChart.Axes(xlValue) '添加坐标轴标题
        .HasTitle = True
        .AxisTitle.Text = "$"
    End With
 
    myChart.ApplyDataLabels '添加数据标签
 
    Set gWorkSheet = Nothing
 
    gWorkBook.Application.Quit
 
    Set gWorkBook = Nothing
    Set gChartData = Nothing
    Set myChart = Nothing
 
End Sub

正如你所见,图表仍然由ChartObject表示并且在本例中由Shape包含。图表在Word中能够由InlineShape或Shape包含,在PowerPoint中由Shape包含。这里,ChartObject一般是在Excel中看到的镜像。一些关键的不同是:

  • 在Excel中属性/方法通常接受一个Range对象,而现在在Word和PowerPoint中接受单元格地址字符串。
  • 在Word和PowerPoint中添加了一个新对象ChartData,访问图表中隐含的链接或嵌入的数据。

编程操作Word和PowerPoint中图表的能力也为围绕在演示期间动态改变图表外观或者创建交互的Word文档的各种各样有趣的解决方案打开了“门”。下面是一个解决方案示例:在演示期间添加数据标签到图表中。

Private Sub BtnDataLabels_Click()
 
    Set myChart = ActivePresentation.Slides(1).Shapes(1).Chart '设置图表对象引用
 
    myChart.ApplyDataLabels '添加数据标签
 
    Set myChart = Nothing
 
End Sub

初译自Excel Team Blog

问题:在实现第一个示例时,发现必须添加对Excel对象库的引用,在添加时发现虽然安装的是Office 14,但仍然是“Microsoft Excel 12.0 Object Library”,并且执行时出现错误:
newchartom1
难道作者的介绍自相矛盾?

相关文章

发表评论