数据透视过滤器和退出函数的捕获错误

Catch Error for Pivot filter and Exit Function

我正在尝试将数据透视字段设置为过滤,如果出现错误(这意味着 Excel 找不到数据),弹出消息错误。

我尝试了 On Error GoTo ErrMsg 但无论过滤器是否有错误都退出了函数。

If country = "All" Then

Else
    With Sheet6.PivotTables("PivotTable1").PivotFields("Operator Country")
        .Orientation = xlPageField
        .Position = 1
    End With
    On Error GoTo ErrMsg
    Sheet6.PivotTables("PivotTable1").PivotFields("Operator Country").CurrentPage _
      = country
    Exit Function 
    
ErrMsg:
    MsgBox ("No data on " & country & "!")

End If

您可以暂停此特定任务的错误处理,然后通过检查 Err.Number 属性.

检查是否出现了错误

例如:

On Error Resume Next
Sheet6.PivotTables("PivotTable1").PivotFields("Operator Country").CurrentPage = country

'check if error occurred
If Err.Number > 0 then
    MsgBox ("No data on " & country & "!")
End If

'resume normal error handling here