使用vb.net更改PowerPoint图表的ChartData

时间:2014-12-11 14:45:54

标签: vb.net interop powerpoint

我有PowerPoint Presentation barchart。现在我想更改此图表的数据。我有一个类(有效)我​​已经有PowerPoint幻灯片对象。我的代码是:

Sub ChangeData(byval sldNr as integer, ChartName as String, byval testValue as Integer)

_pptSld = _pptPre.Slides(sldNr)

    Dim oWorkBook As Excel.Workbook
    Dim oWorkSheet As Excel.Worksheet

    Try
        oWorkBook = CType(_pptSld.Shapes(ChartName).Chart.ChartData.Workbook, Excel.Workbook)
        oWorkSheet = CType(oWorkBook.Sheets(1), Excel.Worksheet)

        With oWorkSheet
            .Range("B2").Value = testValue
    Catch ex As Runtime.InteropServices.COMException
        MsgBox(ex.Message, MsgBoxStyle.Exclamation)

    Catch ex As Exception
        MsgBox(ex.Message.ToString)
    End Try
end sub

我在行

中收到错误hresulte e_fail-error
oWorkBook = CType(_pptSld.Shapes(ChartName).Chart.ChartData.Workbook, Excel.Workbook)

错误很一般,我只是看不出这里有什么问题。在其他函数中我已经使用了_pptSld,所以没有错。如果有人能在这里帮助我会很棒。

1 个答案:

答案 0 :(得分:2)

我自己就找到了答案。首先,您必须激活ChartData Object,然后必须在将数据导入更新工作表后刷新数据源。

她的作用是什么:

         _pptSld = _pptPre.Slides(2)
        _pptChar = _pptSld.Shapes(2).Chart
        _pptChartData = _pptChar.ChartData
        _pptChartData.Activate()

        oWorkBook = CType(_pptSld.Shapes(2).Chart.ChartData.Workbook, Excel.Workbook)
        oWorkSheet = CType(oWorkBook.Sheets(1), Excel.Worksheet)

        With oWorkSheet
            .Range("B2").Value = 30
            _pptChar.Refresh()
        End With

        oWorkBook.Close()