使用VBA刷新数据透视表

我试图自动刷新与Powershell脚本调用Excel中的VBA代码的数据透视表。 我的powershell代码是以下。

$excel = new-object -comobject excel.application $workbook = $excel.workbooks.open("$para_temp\RapportPalettes.xlsm") $worksheet = $workbook.worksheets.item("source") $excel.Run('Import') $worksheet = $workbook.worksheets.item("TCD") $excel.Run('MAJ') 

第一个macros“导入”工作得很好。 但是第二个用来源中的新数据刷新数据透视表的“MAJ”却没有

我在maj首先尝试了这个macros:

 Sub maj() Dim pt As PivotTable Set pt = ActiveSheet.PivotTables("TCD") pt.RefreshTable End Sub 

我没有得到任何错误,但我的翻转表不刷新,我必须手动。

然后我尝试这个来更改数据透视表的数据源:

 Sub MAJ() Dim sht As Worksheet Dim SrcData As String Dim pvtCache As PivotCache 'Determine the data range you want to pivot Set sht = ThisWorkbook.Worksheets("Source") SrcData = sht.Name & "!" & Range("A1:Z10000").Address(ReferenceStyle:=xlR1C1) 'Create New Pivot Cache from Source Data Set pvtCache = ActiveWorkbook.PivotCaches.Create( _ SourceType:=xlDatabase, _ SourceData:=SrcData) 'Change which Pivot Cache the Pivot Table is referring to Worksheets("TCD").Activate ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache) End Sub 

但是我在VBA中有一个438错误:对象不支持此行的属性或方法

 ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache) 

能否请你帮忙 ?

编辑:

正如你所看到的,我有一个工作表和一个名为TCD的数据透视表。 Worsheet

数据透视表

编辑:实际上,macros正在工作,我testing它创build一个button,调用它。 当我用powershell调用它时,它不起作用

尝试使用下面的代码刷新工作表"TCD"中已更新的PivotCache名为"TCD"PivotTable PivotCache

 Option Explicit Sub MAJ() Dim sht As Worksheet Dim SrcData As String Dim pvtCache As PivotCache Dim pvtTbl As PivotTable 'Determine the data range you want to pivot Set sht = ThisWorkbook.Worksheets("Source") SrcData = sht.Range("A1:Z10000").Address(False, False, xlA1, xlExternal) 'Create New Pivot Cache from Source Data Set pvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=SrcData) 'Set the pivot table object Set pvtTbl = ThisWorkbook.Worksheets("TCD").PivotTables("TCD") With pvtTbl .ChangePivotCache pvtCache 'Change which Pivot Cache the Pivot Table is referring to .RefreshTable ' refresh the Pivot Table End With End Sub 

我终于find了一个有点愚蠢的问题。 事实上,我刷新了数据透视表,但我没有保存这些变化。 这是我最终使用的macros,我使用了相同的PowerShell脚本

 Sub Test() Application.DisplayAlerts = False Dim TCD As PivotTable For Each TCD In Worksheets("TCD").PivotTables TCD.RefreshTable Next ThisWorkbook.Save Application.DisplayAlerts = False End Sub 

感谢所有