在 Excel 2007 VBA 中刷新数据透视表不起作用

Refreshing PivotTable in Excel 2007 VBA doesn't work

我正在尝试在刷新源 sql 数据 table 后从 VBA 更新数据透视表 table。无论我做什么,Pivot Table 只会在 第二次 执行此代码时刷新。我已经尝试了 pivot.RefreshTable 和 pivot.Update 的所有组合和顺序,添加 Do Events,将 Application.ScreenUpdating 设置为 false before 和 True after。我 运行 没主意了。每次在 SQL 中修改数据时,我都必须执行一次才能在源 table 中看到它,然后再次在数据透视 table.

中看到它
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

确保连接不会在后台刷新:

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