VBA刷新数据透视表

6

我正在使用代码刷新数据透视表,并且它已经起作用了,但是我在错误处理程序中遇到了困难,它给了我以下错误信息:

对象变量与块变量未设置

这是我正在使用的代码:

Sub RefreshAllPivots()

On Error GoTo Errhandler

  Dim pivotTable As pivotTable
  For Each pivotTable In ActiveSheet.PivotTables
    pivotTable.RefreshTable
  Next

Errhandler:

     MsgBox "Error Refreshing " & pivotTable.Name

MsgBox "All Pivots Refreshed"

End Sub

非常感谢

2个回答

6

只有在出现错误时才需要显示错误信息。此外,您可能希望检查错误是否发生在分析表对象被分配的过程中:

Sub RefreshAllPivots()
    On Error GoTo ErrHandler

    Dim pt As PivotTable
    For Each pt In ActiveSheet.PivotTables
        pt.RefreshTable
    Next pt
ErrHandler:
    If err Then
        If Not pt Is Nothing Then
            MsgBox "Error Refreshing " & pt.Name
        Else
            MsgBox "Unexpected error"
        End If
    Else
        MsgBox "All Pivots Refreshed"
    End If
End Sub

请注意,我将您的变量pivotTable重命名为pt - 使用保留字作为变量名不是好的编程实践。

1
错误“对象变量或 With 块变量未设置”是由于在For Each pivotTable In ActiveSheet.PivotTables循环后未声明 pivotTable.Name 引起的。
只有在该循环内分配该变量才会给其赋值。在错误处理程序之前使用Exit Sub是VBA中的最佳实践。
Sub RefreshAllPivots()

    On Error GoTo Errhandler

    Dim pivotTable As pivotTable
    For Each pivotTable In ActiveSheet.PivotTables
        pivotTable.RefreshTable
        Debug.Print pivotTable.Name
    Next

    MsgBox "All Pivots Refreshed"
    Exit Sub

Errhandler:        
    MsgBox "Error Refreshing " & pivotTable.Name

End Sub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接