Tuesday, December 8, 2020

Change the range of source data of a pivot table programmatically using VBA

 
Option Explicit

Sub Copy_Paste_To_DPR_Pivot()
'Find the last used row in both sheets and copy and paste data below existing data.

Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lcopyLastRow As Long
Dim lDestLastRow As Long

'Open method requires full file path to be referenced.

Workbooks.Open "C:\Users\allso\Desktop\new vba projects\new project subham brother\DPR NOV 2020.xlsb"

  'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("New Raw File Dual@.xlsb").Worksheets("NEW")
  Set wsDest = Workbooks("DPR NOV 2020.xlsb").Worksheets("RAW FILE")
    
 
 
  'clear content on the destination sheet except header
 
  wsDest.Rows("2:" & wsDest.Rows.Count).ClearContents
 
   '1. Find last used row in the copy range based on data in column A
  lcopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
 
 
  'Copy range to clipboard
  wsCopy.range("A2:P" & lcopyLastRow).Copy
 
  'PasteSpecial to paste values, formulas, formats, etc.
  wsDest.range("A2").PasteSpecial Paste:=xlPasteValues
    
    'arrange and refresh the pivot table
    
    'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("DPR NOV 2020.xlsb").Worksheets("RAW FILE")
  Set wsDest = Workbooks("DPR NOV 2020.xlsb").Worksheets("PIVOT")
  lcopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row
  Dim datarange As String
 
   datarange = wsCopy.Name & "!" & range("A1:P" & lcopyLastRow).Address(ReferenceStyle:=xlR1C1)
   
   
   


        
        wsDest.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _
        PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        datarange)
 
 
 

  'Close the workbook

  Workbooks("DPR NOV 2020.xlsb").Close SaveChanges:=True
 
End Sub




No comments:

Post a Comment