如何使用VBA更改PowerPoint中图表的默认数据



我想创建一个集群柱状图,并将其添加到PowerPoint幻灯片中。我不想在Excel中创建该图,然后使用PowerPoint.Slide.Shapes.PasteSpecial方法复制它。我可以创建图表,并在有限的范围内与之交互(例如,我可以禁用图例,请参阅代码(。但是,我不知道如何编辑图表所引用的数据。

Private Sub AddGraph()
' Create a new slide
Dim PowerPointApplication As PowerPoint.Application
Set PowerPointApplication = New PowerPoint.Application
Dim Presentation As PowerPoint.Presentation
Set Presentation = PowerPointApplication.Presentations(1)
Dim Slide As PowerPoint.Slide
Set Slide = Presentation.Slides.Add(Presentation.Slides.Count + 1, ppLayoutText)
' Remove the existing shape 2
Slide.Shapes(2).Delete
' Add the chart
Slide.Shapes.AddChart _
Type:=xlColumnClustered
With Slide.Shapes(2).Chart
.Legend.Delete
' Try to edit some of the default data of the cluster column chart
' This causes a Subscript out of Range error 
WorkBooks("Chart in Microsoft PowerPoint").Cells(2,1) = 2021

End With
End Sub

当PowerPoint创建图表时,它似乎还创建了一个临时(?(Excel工作簿来存储数据。我试图访问该工作簿以编辑默认数据,例如WorkBooks("Chart in Microsoft PowerPoint").Cells(2,1) = 2021,但这会引发"下标超出范围"错误。

有没有办法编辑在PowerPoint中创建图表时创建的Excel工作簿?我是不是在一条没有结果的路上走得太远了;有没有一种更简单的方法可以做到这一点(不包括在Excel工作簿中创建所有内容,然后将该图表复制到PowerPoint演示文稿中(?

ChartData是缺少的链接。以下是更改工作表值的典型代码:

With Slide.Shapes(2).Chart
With .ChartData
.Activate
strText = .Workbook.Worksheets(1).Range("B2").Value
strText = Replace(strText, "4.3", "5.2")
.Workbook.Worksheets(1).Range("B2").Value = strText
.Workbook.Close
End With
End With

最新更新