VBA刷新数据透视

时间:2018-11-05 08:43:11

标签: excel vba excel-vba excel-2010

我正在使用代码刷新Pivots,并且可以正常工作,但是我陷入了错误处理程序的束缚,它给了我:

  

未设置块变量的对象变量

这是我正在使用的代码:

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 个答案:

答案 0 :(得分:6)

仅在出现错误时才显示错误消息。此外,您可能希望检查在分配数据透视表对象时是否发生了错误:

['sasha', 'will']

请注意,我将您的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-使用保留字作为变量名不是一个好习惯。

答案 1 :(得分:1)

抛出错误“未设置块变量的对象变量”,因为pivotTable.Name循环后未声明For Each pivotTable In ActiveSheet.PivotTables

仅在该循环内将此变量分配给一个值。错误处理程序之前的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