I have been trying to tweak this for a long time, and I'm sure there is an easy fix for this, I just haven't figured it out.
My goal is to automatically update the Pivot Table based on the new data in the worksheet with Headings on row 5. Any help would be greatly appreciated. Thank You in advance.
My goal is to automatically update the Pivot Table based on the new data in the worksheet with Headings on row 5. Any help would be greatly appreciated. Thank You in advance.
Code:
Sub AdjustPivotDataRange()
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 = ActiveWorkbook.Worksheets("Completed Projects")
Set Pivot_sht = ActiveWorkbook.Worksheets("Current Cycle Time BB.MBB")
'Enter in Pivot Table Name
PivotName = "Pivot7"
'Dynamically Retrieve Range Address of Data
Set StartPoint = Data_sht.Range("A5")
Set DataRange = Data_sht.Range(StartPoint, StartPoint.SpecialCells(xlLastCell))
NewRange = Data_sht.Name & "!" & _
DataRange.Address(ReferenceStyle:=xlR1C1)
'Make sure every column in data set has a heading and is not blank (error prevention)
If WorksheetFunction.CountBlank(DataRange.Rows(1)) > 0 Then
MsgBox "One of your data columns has a blank heading." & vbNewLine _
& "Please fix and re-run!.", vbCritical, "Column Heading Missing!"
Exit Sub
End If
'Change Pivot Table Data Source Range Address
Pivot_sht.PivotTables(Pivot7).ChangePivotCache _
ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=NewRange)
'Ensure Pivot Table is Refreshed
Pivot_sht.PivotTables(Pivot7).RefreshTable
End Sub