简体   繁体   English

在MS Access中使用VBA刷新Excel Pivot Table数据源

[英]Refreshing an Excel Pivot Table data source with VBA in MS Access

I prefer producing an Excel report that has no links in it, so that it is lightweight and can easily be emailed. 我更喜欢生成一个没有链接的Excel报表,以便它是轻量级的并且可以通过电子邮件轻松发送。

So I have this report that I generate from MS Access - it writes the table to the TAB of a workbook that I have previously built a Pivot Table that uses that tab as it's source. 因此,我具有从MS Access生成的此报告-该表将表写入我先前已构建使用该选项卡作为源的数据透视表的工作簿的TAB中。

What I can't seem to get working properly is 我似乎无法正常工作的是

xlPivot.PivotTables("pvAFP").RefreshTable

My code is as follows: 我的代码如下:

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

Would be nice to be ready to use, because the user needs to "Refresh ALL", before anything can be done to the Pivot Table 准备好使用就好了,因为用户需要先“刷新全部”,然后才能对数据透视表进行任何操作

看看这是否适合您:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM