用于根据单元格值设置数据透视表字段的宏

时间:2018-09-05 02:39:59

标签: excel vba excel-vba

我试图弄清楚如何编写宏以基于单元格值设置数据透视过滤器

A1 = today()

我想将我的数据透视滤镜设置为在运行宏时根据单元格A1自动选择滤镜。有人可以教我正确的代码来做到这一点吗?

1 个答案:

答案 0 :(得分:0)

以下是您的示例:

Option Explicit

Sub main()

Dim wb As Workbook
Dim ws As Worksheet
Dim PC As PivotCache
Dim PT As PivotTable
Dim PF As PivotField
Dim PI As PivotItem
Dim rng As Range

    Set wb = ActiveWorkbook
    Set ws = ActiveSheet
    Set rng = Range("D2:F8")

    Set PC = wb.PivotCaches.Create(xlDatabase, rng)
    Set PT = PC.CreatePivotTable(ws.Range("H1"), "MyTable")
    Set PF = PT.PivotFields("category 1")

   With PF
    .Orientation = xlRowField
    .Position = 1
    .PivotFilters.Add2 xlCaptionEquals, Value1:=ws.Range("A2")
   End With
End Sub

enter image description here