vba中的数据透视表过滤器无法正常工作

时间:2017-02-10 23:33:24

标签: excel vba excel-vba

我有这段代码来选择日期并更改数据透视表的过滤器以反映相关信息。但有时候这种方法有效,有时它给了我

  

错误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

1 个答案:

答案 0 :(得分:0)

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

下面的代码我使用PivotTable类型的对象来定义和设置数据透视表,以及PivotField

我还添加了另一种类型InputBox,强制用户输入Date格式的值。

注意:有可能在数据透视表中的任何位置找不到InputBox中选择的值,所以我添加了一种在代码中检查它的方法下方。

<强>代码

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