VBA不更新数据透视表日期范围

时间:2015-07-12 18:26:46

标签: excel excel-vba vba

我不知道我哪里出错了,但它既没有发挥任何错误也没有工作。我正在尝试使用单元格值更新我的数据透视表,该单元格值应过滤单元格G3中的给定日期范围。 G4。但遗憾的是没有更新表格。

以下是我正在使用的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

1 个答案:

答案 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