将单元格中的date插入到数据透视表中以将其用作filter

我很新的VBA。 我会解释我的项目。

我有一个Excel工作表,有很多我想要过滤的信息。 目前我的代码如下所示:

With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _ "CREATION_DATE") .Orientation = xlPageField .Position = 1 End With ActiveSheet.PivotTables("Tableau croisé dynamique2").AddDataField ActiveSheet. _ PivotTables("Tableau croisé dynamique2").PivotFields("AMOUNT"), _ "Nombre de AMOUNT", xlCount With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields("STATUS") .Orientation = xlRowField .Position = 1 End With With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _ "VENDOR_NAME") .Orientation = xlRowField .Position = 2 End With With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _ "INVOICE_NUM") .Orientation = xlRowField .Position = 3 End With With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _ "Nombre de AMOUNT") .Caption = "Somme de AMOUNT" .Function = xlSum End With ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _ "CREATION_DATE").CurrentPage = "08/09/2016" 

此代码的工作提取过滤date08/09/2016。 现在,我想让数据透视表在启动代码之前在单元格中获取这个date。

但我不想每次都去代码来改变我想要的date。

我想这样的事情:例如:我写在单元格“A1”“09/09/2016”

 ActiveSheet.PivotTables("Tableau croisé dynamique2").PivotFields( _ "CREATION_DATE").CurrentPage = "A1" 

但是我得到一个debugging错误。

经过一些testing,我find了原因(在我的Excel书上)。 这是有关格式化数据透视字段“ CREATION_DATE ”,一旦我添加了它的工作以下部分。

 Set PvtFld = PvtTbl.PivotFields("CREATION_DATE") With PvtFld .Orientation = xlPageField .NumberFormat = "dd/mm/yyyy" ' << this line .Position = 1 End With 

而对于完整的代码:

 Sub PivotFilterDate() Dim PvtTbl As PivotTable Dim PvtFld As PivotField ' set your Pivot Table (after created) to a variable Set PvtTbl = Sheets("PivotSpanish").PivotTables("Tableau croisé dynamique2") ' Set "CREATION_DATE" to a Pivot Field variable Set PvtFld = PvtTbl.PivotFields("CREATION_DATE") With PvtFld .Orientation = xlPageField .NumberFormat = "dd/mm/yyyy" .Position = 1 End With ' you can modify your code to change all field setting, like following 2: With PvtTbl.PivotFields("STATUS") .Orientation = xlRowField .Position = 1 End With With PvtTbl.PivotFields("VENDOR_NAME") .Orientation = xlRowField .Position = 2 End With ' clear previous filters PvtFld.ClearAllFilters ' --- trapping errors --- ' added a Boolean Flag to trap scenarios where no Pivot Item found that matches the value in Cell A1 Dim PvtItemExists As Boolean PvtItemExists = False ' check all Pivot items in Pivot Field ("CREATION_DATE") For Each PvtItem In PvtFld.PivotItems ' check if current Pivot Item equals the value in Cell A1 If PvtItem.Value = CStr(CDate(Range("D1").Value)) Then PvtItemExists = True Exit For End If Next PvtItem If PvtItemExists Then PvtFld.CurrentPage = CStr(CDate(Range("D1").Value)) Else MsgBox "No data matches for date " & CDate(Range("D1").Value) & " in Pivot Table", vbCritical End If End Sub