2015-07-12 72 views
0

我不知道我要去哪裏錯,但它不工作也沒有提供任何錯誤。我正在嘗試使用單元格值更新我的數據透視表,這些值應該過濾單元格G3 & G4中給定的日期範圍。但不幸的是沒有更新表格。VBA不更新數據透視表日期範圍

下面是我正在使用的VBA。

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 

'This line stops the worksheet updating on every change, it only updates when cell 
'G3 or G4 is touched 

If Intersect(Target, Range("G3:G4")) Is Nothing Then Exit Sub 

'Set the Variables to be used 
Dim pt As PivotTable 
Dim Field As PivotField 
Dim EDate As String 
Dim SDate As String 

'Here you amend to suit your data 
Set pt = Worksheets("Report").PivotTables("PivotTable1") 
Set Field = pt.PivotFields("Date") 
SDate = Worksheets("Report").Range("G3").Value 
EDate = Worksheets("Report").Range("G4").Value 


'This updates and refreshes the PIVOT table 
With pt 
Field.ClearAllFilters 
Field.PivotFilters.Add Type:=xlDateBetween, Value1:=SDate, Value2:=EDate 
pt.RefreshTable 

End Sub 
+3

它適合我。我注意到你錯過了'End With'語句。此外,您是否將代碼放在工作表模塊中用於「報告」? –

+0

是的。我有同樣的錯誤。插入結束與現在它工作。謝謝。 –

回答

0

我能夠自己解決它。發佈下面的答案,可能是某人的幫助。

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 

'This line stops the worksheet updating on every change, it only updates when cell 
'G3 or G4 is touched 

If Intersect(Target, Range("G3:G4")) Is Nothing Then Exit Sub 

'Set the Variables to be used 
Dim pt As PivotTable 
Dim Field As PivotField 
Dim EDate As String 
Dim SDate As String 

'Here you amend to suit your data 
Set pt = Worksheets("Report").PivotTables("PivotTable1") 
Set Field = pt.PivotFields("Date") 
SDate = Worksheets("Report").Range("G3").Value 
EDate = Worksheets("Report").Range("G4").Value 


'This updates and refreshes the PIVOT table 
With pt 
Field.ClearAllFilters 
Field.PivotFilters.Add Type:=xlDateBetween, Value1:=SDate, Value2:=EDate 
pt.RefreshTable 
End With 

End Sub