如何在excel中动态更新数据透视表?
上面的代码抛出一个运行时错误5。我试着尽我所能去修复它,但我无能为力。谁能帮我一下吗如何在excel中动态更新数据透视表?,excel,vba,dynamic,range,pivot-table,Excel,Vba,Dynamic,Range,Pivot Table,上面的代码抛出一个运行时错误5。我试着尽我所能去修复它,但我无能为力。谁能帮我一下吗 我正在尝试动态更新透视表的范围。请澄清哪一行代码会引发错误。反复按F9,直到得到确切的错误消息。使用特定的错误消息发回。 Option Explicit Sub DPTR() With Application .Calculation = xlCalculationManual .EnableEvents = False .ScreenUpdating = False End
我正在尝试动态更新透视表的范围。请澄清哪一行代码会引发错误。反复按F9,直到得到确切的错误消息。使用特定的错误消息发回。
Option Explicit
Sub DPTR()
With Application
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
Dim startcell As Range, lastRow As Long, lastCol As Long
Dim ws, wsPivot As Worksheet
Dim pvtName As String, rngPivot As Range, strNewData As String
Set ws = ThisWorkbook.Worksheets(4)
Set wsPivot = Sheet8
pvtName = "CFN"
Set startcell = ws.Range("A1")
lastRow = ws.Cells(ws.Rows.Count, startcell.Column).End(xlUp).Row
lastCol = ws.Cells(startcell.Row + 1, ws.Columns.Count).End(xlToLeft).Column
Set rngPivot = ws.Range(startcell, ws.Cells(lastRow, lastCol))
strNewData = ws.Name & "!" & rngPivot.Address(ReferenceStyle:=xlR1C1)
'If WorksheetFunction.CountBlank(rngPivot.Rows(1)) > 0 Then
'MsgBox "One of the source data columns contains a blank heading." & vbNewLine _ & "Please add a
heading and run the macro again", vbCritical, _
'"Source data Column heading missing"
'On Error GoTo Reset
'End If
wsPivot.PivotTables(pvtName).ChangePivotCache ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase,
SourceData:=strNewData)
wsPivot.PivotTables(pvtName).RefreshTable
Reset:
With Application
.Calculation = xlCalculationAutomatic
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub