问题
I have a PowerPoint presentation with ~200 slides. Each slide has one chart, with data that is updated monthly by a link to a master xlsx file.
To not show empty values (future months) in the charts, I open the data editor (chart right click > Edit data...) of every chart and select the range until the current month.
I wrote a macro for it in PowerPoint:
Sub Refresh_slides()
For i = 1 To ActivePresentation.Slides.Count
Set ObjSlide = ActivePresentation.Slides(i)
On Error Resume Next
Set mychart = ObjSlide.Shapes("Chart 3").Chart
mychart.Select
mychart.ChartData.Activate
Set wb = mychart.ChartData.Workbook
Set ws = wb.Worksheets(1)
Application.Run "Refresh_slides_AUX.xlsm!atual_slide"
wb.Close True
Next
End Sub
Refresh_slides_AUX.xlsm
is an auxiliary macro worksheet to select the correct range of each chart (because PowerPoint VBA, as far as I know, don't have an option to do it):
Sub atual_slide()
Windows("Gráfico no Microsoft PowerPoint").Activate
ActiveSheet.ListObjects("Table1").Resize Range("$A$1:$I$23")
ActiveWindow.Close SaveChanges:=True
End Sub
The result is:
BEFORE: AFTER:
It works, but after the range is resized the charts don’t change, they still looking like the BEFORE picture.
I know the process is right because if I do the resizing manually (right corner of the dotted line) the chart is updated correctly.
回答1:
Add wb.Application.Update before wb.Close
See if that helps.
回答2:
This is an old question but I had trouble finding an answer and this question came up as the first hit for my search.
I'd like to post a powerpoint vba routine that has an ActivateChartDataWindow method that I found was necessary to refresh the chart after I had updated the data.
Private Sub RefreshChart(slideName As String, shapeName As String, spName As String, dataRange As String)
'Add reference to Microsoft ActiveX Data Object 6.x Library
'Read data point info from SQL
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connStr As String
Dim query As String
Dim sld As Slide
Dim shp As Shape
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Set sld = ActivePresentation.Slides(slideName)
Set shp = sld.Shapes(shapeName)
Set xlWB = shp.Chart.ChartData.Workbook
Set xlWS = xlWB.Sheets(1)
xlWS.Range(dataRange).Clear
Set conn = New ADODB.Connection 'CreateObject("adodb.connection")
connStr = "Provider=SQLOLEDB;Data Source='" & SQLServer & "';Initial Catalog=WVCore;Integrated Security=SSPI;"
conn.Open connStr
Set rs = New ADODB.Recordset 'CreateObject("adodb.recordset")
query = "exec " & spName 'usp_WVCRevenue
With rs
.ActiveConnection = conn
.Open query
xlWS.Range("A2").CopyFromRecordset rs 'Leave headings in tact
.Close
End With
shp.Chart.ChartData.ActivateChartDataWindow
xlWB.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
End Sub
来源:https://stackoverflow.com/questions/34396567/how-to-update-a-chart