OpenOffice Calc宏添加饼图

时间:2014-06-24 15:00:34

标签: macros charts openoffice-calc basic

我正在尝试使用宏在开放式办公室中插入一个饼图。但代码显示错误:

行:

  

Dim oDiagram As New com.sun.star.chart.PieDiagram

错误:

  

"Object not accessible. Invalid reference."

我无法弄清楚原因。请帮助。这是我完整的宏代码:

Sub Macro1

    Dim oRange as Object
    Dim oRangeAddress(1) As New com.sun.star.table.CellRangeAddress
    Dim oDiagram As New com.sun.star.chart.PieDiagram
    Dim oRect As New com.sun.star.awt.Rectangle
    Dim cTitle as String

    oRange = thisComponent.getCurrentSelection.getRangeAddress
    oSheets = ThisComponent.getSheets()
    oSheet = oSheets.getByIndex(0)
    oCharts = oSheet.Charts

    oRect.Width = 10000
    oRect.Height = 10000
    oRect.X = 8000
    oRect.Y = 1000

    oRangeAddress(0).Sheet = oRange.Sheet
    oRangeAddress(0).StartColumn = 0
    oRangeAddress(0).StartRow = 0
    oRangeAddress(0).EndColumn = 1
    oRangeAddress(0).EndRow = 2

    cTitle = "Test Results"
    oCharts.addNewByName(cTitle,oRect,oRangeAddress(),TRUE, TRUE)
    oChart = oCharts.getByName(cTitle).embeddedObject
    oChart.Diagram = oDiagram
    oChart.HasMainTitle = True
    oChart.Title.String = cTitle

End Sub

以下是输入表数据:

Input sheet data.

1 个答案:

答案 0 :(得分:0)

您无法直接实例化com.sun.star.chart.PieDiagram,而与已存在的图表无关。相反,您必须先创建图表,然后创建PieDiagram。因此,要使宏工作,请执行以下操作:

  • 删除第Dim oDiagram As New com.sun.star.chart.PieDiagram
  • 将行oChart.Diagram = oDiagram更改为oChart.Diagram = oChart.createInstance("com.sun.star.chart.PieDiagram")

这导致以下代码(我在Win7上使用OpenOffice.org Calc 4.1.0对此进行了测试):

Sub Macro1

    Dim oRange as Object
    Dim oRangeAddress(1) As New com.sun.star.table.CellRangeAddress
    Dim oRect As New com.sun.star.awt.Rectangle
    Dim cTitle as String

    oRange = thisComponent.getCurrentSelection.getRangeAddress
    oSheets = ThisComponent.getSheets()
    oSheet = oSheets.getByIndex(0)
    oCharts = oSheet.Charts

    oRect.Width = 10000
    oRect.Height = 10000
    oRect.X = 8000
    oRect.Y = 1000

    oRangeAddress(0).Sheet = oRange.Sheet
    oRangeAddress(0).StartColumn = 0
    oRangeAddress(0).StartRow = 0
    oRangeAddress(0).EndColumn = 1
    oRangeAddress(0).EndRow = 2

    cTitle = "Test Results"
    oCharts.addNewByName(cTitle,oRect,oRangeAddress(),TRUE, TRUE)
    oChart = oCharts.getByName(cTitle).embeddedObject
    oChart.Diagram = oChart.createInstance("com.sun.star.chart.PieDiagram")
    oChart.HasMainTitle = True
    oChart.Title.String = cTitle

End Sub

运行宏应该给出以下结果:

Pie Chart created by Basic macro

注意:宏不会在LibreOffice Calc上运行;它只适用于OpenOffice.org Calc。我认为这是一个LibreOffice错误,因为我发现在OOo和LO的API中没有任何差异。