2010-01-03 49 views
0

我有一個連接到Access數據庫查詢的Excel透視圖緩存。但是,如果我在Access中更改源數據(例如,更改值,添加/刪除記錄),則必須刷新pivotcache,然後再次運行該查詢以檢索整個數據集上的所有記錄。這是非常低效的。我只想檢索頻繁更改的記錄(理想情況下,只有記錄發生變化,但這將是未來的考慮因素)。MS Excel 2003:部分刷新PivotCache或組合數據透視緩存

我曾嘗試下面的解決方案,但它們不適合我的目的:
*在同一工作表在Excel中創建兩個查詢表,包含兩個查詢表,整個工作表上創建數據透視表。我只刷新「當前」查詢表。但是,我限於65536行,這比我的查詢中的記錄數少。
*創建兩個數據透視表。但是,這對於用戶必須設置兩次數據透視表的過程非常費力。我希望優化發生在幕後,而不是用戶必須改變他們的習慣。

我現在考慮的潛在解決方案是使用兩個ADO記錄集(一個用於歷史數據)刷新pivotcache,另一個用於更新頻繁的當前數據。如果我更改當前數據,則只運行當前數據集的查詢。

但是,我似乎無法將pivotcache轉換爲ADO記錄集。行「pvtRecordset.MoveFirst」會引發錯誤。它用於測試目的。如果該行不起作用,那麼我無法使用rsCombineRecordsets函數將新記錄集與pivotcache組合起來。

另一種方法是將ADO記錄集轉換爲pivotcache(即設置pivotcache.recordset = ADOrecordset)。歷史數據上的ADO記錄集被保存到內存中,所以我們只需要打開記錄集一次。但是,我不知道如何讓這個工作。數據透視表數據保持不變,因爲它仍然顯示「strSqlHist」的結果,而不是「strSqlHist」和「strSqlCurr」的組合。

Sub Main() 
    RefreshPivotCache "CURRENT" 
End Sub 

Public Function RefreshPivotCache(strRefreshCmd As String) 
    Dim cnn As New ADODB.Connection 
    Dim rst As New ADODB.Recordset 
    Dim pvtCache As PivotCache 
    Dim pvtRecordset As ADODB.Recordset 
    Dim ptt As PivotTable 
    Dim strSqlHist As String, strSqlCurr As String 
    Dim strCon As String 
    Dim rstCollection As New Collection 

    strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ 
    "Data Source=I:\Cash Management\Cash_M.mdb;" 

    strSqlHist = "SELECT * FROM v_CFMT WHERE Trx_Date < DateValue('01-DEC-2009')" 
    strSqlCurr = "SELECT * FROM v_CFMT WHERE Trx_Date >= DateValue('01-DEC-2009')" 

    If strRefreshCmd = "NEW" Then 

     'Open the connection and fill the Recordset. 
     cnn.Open strCon 
     Set rst = cnn.Execute(strSqlHist) 

     'Add pivot cache and assign the cache source to the recordset 
     Set pvtCache = ThisWorkbook.PivotCaches.Add(SourceType:=xlExternal) 
     Set pvtCache.Recordset = rst 

     'Create pivot table and assign to pivot cache 
     Set ptt = pvtCache.CreatePivotTable(TableDestination:=ActiveCell, TableName:="PT_ADO") 

    ElseIf strRefreshCmd = "CURRENT" Then 
     'Open the connection and fill the Recordset. 
     cnn.Open strCon 
     Set rst = cnn.Execute(strSqlCurr) 

     'Convert pivotcache to recordset - does not work 
     Set pvtRecordset = ActiveCell.PivotTable.PivotCache.Recordset 
     pvtRecordset.MoveFirst 'Operation is not allowed when the object is closed 

     'Combine the two recordsets and assign to the pivotcache recordset 
     rstCollection.Add pvtRecordset 
     rstCollection.Add rst 
     Set pvtRecordset = rsCombineRecordsets(rstCollection) 'custom function. 

    End If 

    'Release objects from memory 
    cnn.Close 
    Set cnn = Nothing 
    If CBool(rst.State And adStateOpen) Then rst.Close 
    Set rst = Nothing 
    Set ptt = Nothing 
    Set rstCollection = Nothing 
End Function 

總之,我該如何部分刷新一個pivotcache或者結合兩個pivotcaches?

回答

相關問題