【问题标题】:Application defined or object defined error vba pivot table应用程序定义或对象定义错误 vba 数据透视表
【发布时间】:2017-03-28 07:10:06
【问题描述】:

尊敬的专家,我正在尝试执行以下 VBA 代码来定义我的数据并刷新数据透视表,但我得到 已定义或对象定义的错误 1004。请指导我在下面做错的地方。

Sub Pivot()

Dim shPivot As Worksheet
Dim shData As Worksheet
Dim lr As Long
Dim lc As Long
Dim rng As Range

Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")

lr = shPivot.Range("A" & Rows.Count).End(xlUp).Row

Set rng = shPivot.Range(Cells(1, 1), Cells(lr, 32))


With shData.PivotTables("PivotTable1").PivotCache
        .SourceData = rng.Address(True, True, xlR1C1, True)
        .Refresh
End With

End Sub

【问题讨论】:

  • 如果您告诉我们错误发生在哪里,通常会有所帮助!您需要使用:Set rng = shPivot.Range(shPivot.Cells(1, 1), shPivot.Cells(lr, 32))
  • 关注@Rory 也关注lr = shPivot.Range("A" & shPivot.Rows.Count).End(xlUp).Row
  • 我在 .SourceData = rng.Address(True, True, xlR1C1, True) 上遇到错误

标签: vba excel


【解决方案1】:

试试下面的代码:

Option Explicit

Sub Pivot()

Dim shPivot As Worksheet
Dim shData As Worksheet
Dim PT As PivotTable
Dim PTCache As PivotCache
Dim lr As Long
Dim lc As Long
Dim Rng As Range

Set shPivot = ActiveWorkbook.Sheets("Data")
Set shData = ActiveWorkbook.Sheets("Pivot")

With shPivot
    lr = .Range("A" & .Rows.Count).End(xlUp).Row
    Set Rng = .Range(.Cells(1, 1), .Cells(lr, 32))
End With

' set the Pivot Cache with the updated Data Source
' Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng)

' === Option 2 : set the Pivot Cache with the updated Data Source ===
Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=shPivot.Name & "!" & Rng.Address(True, True, xlR1C1, False))

' Set the Pivot Table to existing "PivotTable1" in "Data" sheet
Set PT = shData.PivotTables("PivotTable1")

With PT
    .ChangePivotCache PTCache
    .RefreshTable
End With

End Sub

【讨论】:

  • 嗨 Shai ,我认为这个答案可以做一些解释 - OP 做错了什么?还有,最后With PT 什么都没做?
  • @CallumDA 感谢With PT 部分:) 关于解释,根据我对PivotTables 的经验,我在代码中添加了cmets,这是最可靠的方法
  • @ShaiRado 先生,我在 Set PTCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Rng) 中遇到类型不匹配错误
  • @sagar 如果您在此行之前添加Debug.Print Rng.Address,您会在即时窗口中得到什么?
  • @ShaiRado $A$1:$AF$14999 反映在正确范围的即时窗口中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多