我有用于创建数据透视表的vba代码,但我想过滤2019年的日期(“预定发货日期”部分)。
'create pivot table
Set pvt2 = pvtcache.CreatePivotTable(TableDestination:=startpvt, TableName:="PivotTable2")
pvt2.PivotFields("Scheduled Ship Date").Orientation = xlRowField
With pvt2.PivotFields("Week")
.Orientation = xlPageField
.Position = 1
End With
With pvt2.PivotFields("Item Type")
.Orientation = xlPageField
.Position = 2
End With
With pvt2.PivotFields("Quantity Ordered")
.Orientation = xlDataField
End With
pvt2.PivotFields("Item Type").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("Item Type").CurrentPage = "KIT"
pvt2.PivotFields("Week").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("Week").CurrentPage = Cells(2, 2).Value
End Sub
答案 0 :(得分:0)
通过更改数据透视表名称,数据透视表列,工作表名称来修改以下代码,然后尝试:
Option Explicit
Sub test()
Dim pf As PivotField
With ThisWorkbook.Worksheets("Sheet1")
Set pf = ActiveSheet.PivotTables("pvtTest").PivotFields("Year")
pf.ClearAllFilters
pf.CurrentPage = "2019"
End With
End Sub
答案 1 :(得分:0)
您的“计划发货日期”包含各个日期,您想将其用作过滤器。
然后,您可以显示CurrentPage
(仅是一个单独的日期,并假定是不需要的日期),或通过以下方式切换每个PivotItem的可见性:
With pvt2.PivotFields("Scheduled Ship Date")
.Orientation = xlPageField
.Position = 1
End With
With pvt2.PivotFields("Item Type")
.Orientation = xlPageField
.Position = 2
End With
With pvt2.PivotFields("Quantity Ordered")
.Orientation = xlDataField
End With
pvt2.PivotFields("Item Type").ClearAllFilters
pvt2.PivotFields("Item Type").CurrentPage = "KIT"
Dim pi As PivotItem
pvt2.PivotFields("Scheduled Ship Date").ClearAllFilters
pvt2.PivotFields("Scheduled Ship Date").EnableMultiplePageItems = True
For Each pi In pvt2.PivotFields("Scheduled Ship Date").Pivotitems
If Year(pi.Value) <> 2019 Then pi.Visible = False
Next pi
请注意,至少一项必须保持可见,因此,如果您没有2019年的日期,则会收到错误消息。
日期过滤器仅适用于行字段或列字段(上述解决方案不适用,其中日期值为页面字段)。如果您将“计划发货日期”作为行字段插入,则可以使用以下任一方法:
pvt2.PivotFields("Scheduled Ship Date").PivotFilters.Add2 _
Type:=xlDateThisYear
或以下:
pvt2.PivotFields("Scheduled Ship Date").PivotFilters.Add2 _
Type:=xlDateBetween, _
Value1:="01.01.2019", _
Value2:="31.12.2019", _
WholeDayFilter:=True