更改数据透视表源数据的范围

时间:2019-11-22 07:29:48

标签: excel vba pivot

我想更新数据透视表从中读取的源数据范围,以使其更加动态,但是我得到了大量的错误代码。

Private Sub CommandButton2_Click()

Dim Data_sht As Worksheet
Dim Pivot_sht As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String

'Set Variables Equal to Data Sheet and Pivot Sheet
  Set Data_sht = Workbooks("bdncasemacro.xlsm").Worksheets("Filter")
  Set Pivot_sht = Workbooks("bdncasemacro.xlsm").Worksheets("Pivot")

'Enter in Pivot Table Name
  PivotName = "PivotTable4"

'Dynamically Retrieve Range Address of Data
  Set StartPoint = Data_sht.Range("A1")
  Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))

  NewRange = Data_sht.Name & "!" & _
    DataRange.Address(ReferenceStyle:=xlR1C1)

'Change Pivot Table Data Source Range Address
  Pivot_sht.PivotTables("PivotTable4").ChangePivotCache _
    Workbooks("bdncasemacro.xlsm").PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=NewRange)

'Ensure Pivot Table is Refreshed
  Pivot_sht.PivotTables(PivotName).RefreshTable

'Complete Message
  MsgBox PivotName & "'s data source range has been successfully updated!"
End Sub

其中一个错误是:

enter image description here

指向代码中不断变化的源地址部分,我是否需要添加任何代码或进行更改?预先感谢!

0 个答案:

没有答案