调用函数VBA时需要运行时错误'424'对象

时间:2019-02-06 14:07:53

标签: excel vba pivot-table

我正在使用此代码更新所有数据透视表的源,但是我总是得到

  

“需要运行时错误'424'对象”。

奇怪的是,将代码放置在函数中的循环内部实际上可以正常工作而不会出现此错误,因此我不认为这是函数的代码,而是我的调用方式。我想知道为什么它不起作用。

Private Sub Workbook_Open()
    For Each st In ActiveWorkbook.Worksheets
        For Each pt In st.PivotTables
            UpdatePivotSource (pt)
        Next
    Next
End Sub

Sub UpdatePivotSource(pt As PivotTable)
    Dim StartPoint As Range
    Dim NewRange As String
    Dim LastCol As Long
    Dim lastRow As Long
    Dim Data_Sheet As Worksheet
    Dim DataRange As Range

    Set Data_Sheet = ThisWorkbook.Worksheets(Split(pt.PivotCache.SourceData, "!")(0))
    Set StartPoint = Data_Sheet.Range("A1")
    LastCol = StartPoint.End(xlToRight).Column
    lastRow = StartPoint.End(xlDown).Row

    Set DataRange = Data_Sheet.Range(StartPoint, Data_Sheet.Cells(lastRow, LastCol))
    NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)

    pt.ChangePivotCache ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
End Sub

1 个答案:

答案 0 :(得分:1)

将子项更改为此:

Private Sub Workbook_Open()
    Dim pt As Object 'or Dim pt As PivotTable
    For Each st In ActiveWorkbook.Worksheets
        For Each pt In st.PivotTables
            UpdatePivotSource pt
        Next
    Next
End Sub

区别在于pt被声明为Object,而pt不在括号内。仅当人们知道发生了什么时,才应谨慎使用VBA参数中的括号。例如,对象是通过引用(ByRef)传递的,而圆括号ByVal则是传递的。

为避免将来出现未声明的变量,请在模块顶部使用“选项显式”-What do Option Strict and Option Explicit do?