【发布时间】:2020-09-29 18:21:13
【问题描述】:
之前我问过关于如何更改数据透视域“行”的问题 (VBA, Application-defined or Object Error, changing Pivot Filter)。但是,更改“过滤器”字段似乎有所不同。
这是我用来使用 vba 更改可透视表“行”值的代码,Period 是我的透视表中的“过滤器”字段。
当我运行它时,我收到一条错误消息Could not apply filter,这是用户错误处理。
Dim pivTable1 As PivotTable
Set pivTable1 = GetPivotTable(ThisWorkbook, "Summary of LoBs", "PivotTable1")
If pivTable1 Is Nothing Then
MsgBox "Missing Pivot Table", vbInformation, "Cancelled"
Exit Sub
End If
pivTable1.PivotCache.Refresh
Dim periodField As PivotField
On Error Resume Next
Set periodField = pivTable1.PivotFields("Period")
On Error GoTo 0
If periodField Is Nothing Then
MsgBox "Missing Pivot Field", vbInformation, "Cancelled"
Exit Sub
End If
periodField.ClearAllFilters
Dim filterDate As Variant
On Error Resume Next
filterDate = ThisWorkbook.Worksheets("Input").Range("H2").Value2
If Err.Number <> 0 Then
Err.Clear
MsgBox "Missing Filter Date", vbInformation, "Cancelled"
Exit Sub
End If
'Try String first
If VarType(filterDate) = vbString Then
periodField.PivotFilters.Add Type:=xlCaptionEquals, Value1:=filterDate
If Err.Number = 0 Then Exit Sub
filterDate = CDbl(CDate(filterDate))
Err.Clear
End If
If VarType(filterDate) <> vbDouble Then
MsgBox "Invalid Filter Date", vbInformation, "Cancelled"
Exit Sub
End If
'Try Date (as Double data type)
periodField.PivotFilters.Add Type:=xlSpecificDate, Value1:=filterDate
If Err.Number <> 0 Then
Err.Clear
MsgBox "Could not apply filter", vbInformation, "Cancelled"
Exit Sub
End If
任何帮助将不胜感激。 谢谢。
【问题讨论】:
-
我觉得有趣的是,使用像“excelguy”这样的用户名你忘记了 excel 标签:-)
-
知道实际的 Err.Number 或错误消息会很有用。
-
错误号是
1004。