vba中的数据透视表filter工作不正常

我有这个代码来select一个date,并更改数据透视表的filter,以反映相关的信息。 但有些时候,这有效,有时它给了我

错误1004应用程序定义或对象定义的错误

这让我疯狂,我不知道发生了什么,特别是因为这个代码起作用,然后没有任何改变。

Dim DataVenda As Date DataVenda = InputBox("Data de Vendas (dd/mm):") ActiveSheet.Range("B1").Select With Selection ActiveSheet.PivotTables("DinTblResumoDiario").PivotFields("Data:").ClearAllFilters ActiveSheet.PivotTables("DinTblResumoDiario").PivotFields("Data:").CurrentPage = DataVenda End With 

该错误是在最后一个命令: ActiveSheet.PivotTables("DinTblResumoDiario").PivotFields("Data:").CurrentPage = DataVenda

像上面所写,最好避免使用ActiveSheetSelectSelection ,而是使用完全限定的对象。

下面的代码我使用typesPivotTable透视表的对象来定义和设置数据透视表,也为透视PivotField

我还添加了另一种types的InputBox ,强制用户inputDate格式的值。

注意 :在InputBoxselect的值有可能在Pivot Table内部的任何地方找不到,所以我添加了一个方法来检查下面的代码。

 Option Explicit Sub OccupancyPivot() Dim wsSheet As Worksheet Dim PT As PivotTable Dim PTFld As PivotField Dim DataVenda As Date ' use this type of Input Box to force the user to enter a date format DataVenda = Application.InputBox("Data de Vendas (dd/mm):", "Select date", FormatDateTime(Date, vbShortDate), Type:=1) Set wsSheet = ThisWorkbook.Worksheets("Sheet1") ' <-- modify "Sheet1" to your Pivot's sheet name On Error Resume Next Set PT = wsSheet.PivotTables("DinTblResumoDiario") ' set the PivotTable On Error GoTo 0 If PT Is Nothing Then ' "DinTblResumoDiario" Pivot Table doesn't exist MsgBox "Pivot Table 'DinTblResumoDiario' doesn't exist!" Else ' "DinTblResumoDiario" Pivot Table exists Set PTFld = PT.PivotFields("Data:") ' <-- set the pivot field PTFld.ClearAllFilters On Error Resume Next PTFld.CurrentPage = DataVenda ' Error line if DataVenda isn't valid (no value inside Pivot Table matches it) If Err.Number <> 0 Then MsgBox "Filter Didn't get applied, no value inside Pivot Table matches your selection" End If On Error GoTo 0 End If End Sub