2015-07-12 65 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