我尝试在刷新源sql数据表后从VBA更新数据透视表。无论我做什么,数据透视表只会刷新第二次执行此代码。我已经尝试了pivot.RefreshTable和pivot.Update的所有组合和订单,添加Do Events,将Application.ScreenUpdating设置为false,之后设置为True。我的想法已经不多了。每次在SQL中修改数据时,我必须执行一次以在源表中查看它,并再次在数据透视表中查看它。
Dim c As WorkbookConnection
Set c = ThisWorkbook.Connections.Item("Sheet1")
sSQL = "Select * from Table1 "
c.OLEDBConnection.CommandText = sSQL
c.OLEDBConnection.CommandType = xlCmdSql
c.Refresh
For Each pivot In ThisWorkbook.Worksheets("Sheet1").PivotTables
pivot.RefreshTable
pivot.Update
pivot.PivotCache.Refresh
DoEvents
pivot.RefreshTable
pivot.Update
pivot.PivotCache.Refresh
Next
答案 0 :(得分:1)
确保连接不在后台刷新:
Dim c As WorkbookConnection
Set c = ThisWorkbook.Connections.Item("Sheet1")
sSQL = "Select * from Table1 "
c.OLEDBConnection.CommandText = sSQL
c.OLEDBConnection.CommandType = xlCmdSql
c.OLEDBConnection.Backgroundquery = False
c.Refresh
For Each pivot In ThisWorkbook.Worksheets("Sheet1").PivotTables
pivot.RefreshTable
Next