使用MS Access中的VBA刷新Excel数据透视表数据源

时间:2015-07-07 21:46:30

标签: excel excel-vba ms-access access-vba pivot-table vba

我更喜欢制作一个没有链接的Excel报表,因此它很轻巧,可以轻松通过电子邮件发送。

所以我有这个从MS Access生成的报告 - 它将表写入工作簿的TAB,我之前已经构建了一个使用该选项卡作为源的数据透视表。

我似乎无法正常工作

xlPivot.PivotTables("pvAFP").RefreshTable

我的代码如下:

Public Sub ViewAFP(strPathToTemplate As String, Optional dbFullPath As String)

'10 Excel objects created
Dim xlApp As Object
Dim WB As Object
Dim xlSheet As Object
Dim xlPivot As Object
Dim rngWorkingRange As Object
Dim intCOL As Integer

Dim db As Database

Dim rsAFP_Pivot As DAO.Recordset
Dim rsAFP_Data As DAO.Recordset



Dim fld As Variant

Dim strLocation As String


'uses the 'My Documents\COB folder of the user
'C:\Users\[username]\Documents\COB
strLocation = "C:\users\" & Environ$("Username") & "\Documents\COB\AFP_Summary_" & DateString & ".xlsx"



Set xlApp = CreateObject("Excel.Application")

Set WB = xlApp.Workbooks.Open(strPathToTemplate)

Set xlSheet = WB.Sheets("AFP DATA")
Set xlPivot = WB.Sheets("AFP PIVOT")



'ALLOW FOR EXTERNAL ENGINES
If Len(dbFullPath) < 1 Then
    Set db = CurrentDb
Else
    Set db = OpenDatabase(dbFullPath, True)
End If


Set rsAFP_Data = db.OpenRecordset("Select * FROM AFP_DATA")

intCOL = 1

For Each fld In rsAFP_Data.Fields
    xlSheet.Cells(1, intCOL).Value = fld.Name
    Debug.Print fld.Name
    intCOL = intCOL + 1
Next


xlSheet.Range("A2").CopyFromRecordset rsAFP_Data


Set rngWorkingRange = xlSheet.Range("A1").CurrentRegion


    xlSheet.ListObjects.Add(xlSrcRange, rngWorkingRange, , xlYes).Name _
        = "AFP_Data"
    xlSheet.ListObjects("AFP_Data").TableStyle = "TableStyleLight9"

'set pvAFP to point to this table
    xlPivot.PivotTables("pvAFP").ChangePivotCache WB.PivotCaches. _
        Create(SourceType:=xlDatabase, SourceData:="AFP DATA!AFP_Data", _
        Version:=xlPivotTableVersion12)



xlPivot.Select

xlPivot.PivotTables("pvAFP").RefreshTable

WB.RefreshAll
WB.SaveAs FileName:=strLocation

xlApp.Quit

Set xlSheet = Nothing
Set fld = Nothing

Set rsAFP_Data = Nothing

Set db = Nothing
Set WB = Nothing
Set xlApp = Nothing

End Sub

准备好使用会很好,因为用户需要“刷新所有”,然后才能对数据透视表做任何事情

1 个答案:

答案 0 :(得分:0)

看看这是否适合你:

xlPivot.PivotTables("pvAFP").PivotCache.Refresh