2015-04-22 105 views
0

我试图在源SQL数据表刷新后从VBA更新数据透视表。无论我做什么,数据透视表只会刷新第二次执行此代码。我尝试了pivot.RefreshTable和pivot.Update的所有组合和顺序,添加了Do Events,将Application.ScreenUpdating设置为false之前和True之后。我正在用尽想法。每次在SQL中修改数据时,我都必须执行一次才能在源表中查看数据,并再次在数据透视表中查看数据。在Excel 2007中刷新数据透视表VBA不起作用

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

你尝试过要通过与破发点,看看它在所有第一次尝试得到更新? – Sam

回答

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 
+0

就是这样!谢谢。 – Lukasz