Forum Discussion
Trying to insert Pivot Table
- Dec 06, 2025
Sub CreatePivotTable()
Dim wb As Workbook
Dim wsData As Worksheet
Dim wsSummary As Worksheet
Dim rngSource As Range
Dim pc As PivotCache
Dim pt As PivotTable' Always point to the workbook that holds this code
Set wb = ThisWorkbook ' Or Workbooks("YourFileName.xlsx")' Source and destination sheets
Set wsData = wb.Worksheets("Year Data")
Set wsSummary = wb.Worksheets("Yearly Summary")' Source range (you can keep it fixed or use CurrentRegion)
Set rngSource = wsData.Range("A3:F24")
' Or:
' Set rngSource = wsData.Range("A3").CurrentRegion' Optional: remove existing pivot with the same name
On Error Resume Next
wsSummary.PivotTables("PivotTable3").TableRange2.Clear
On Error GoTo 0' 1) Create the PivotCache
Set pc = wb.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=rngSource, _
Version:=xlPivotTableVersion14)' 2) Create the PivotTable from that cache
Set pt = pc.CreatePivotTable( _
TableDestination:=wsSummary.Range("A3"), _
TableName:="PivotTable3", _
DefaultVersion:=xlPivotTableVersion14)' (Optional) select the top-left cell of the new pivot
wsSummary.Activate
wsSummary.Range("A3").SelectEnd Sub
Sub CreatePivotTable()
Dim wb As Workbook
Dim wsData As Worksheet
Dim wsSummary As Worksheet
Dim rngSource As Range
Dim pc As PivotCache
Dim pt As PivotTable
' Always point to the workbook that holds this code
Set wb = ThisWorkbook ' Or Workbooks("YourFileName.xlsx")
' Source and destination sheets
Set wsData = wb.Worksheets("Year Data")
Set wsSummary = wb.Worksheets("Yearly Summary")
' Source range (you can keep it fixed or use CurrentRegion)
Set rngSource = wsData.Range("A3:F24")
' Or:
' Set rngSource = wsData.Range("A3").CurrentRegion
' Optional: remove existing pivot with the same name
On Error Resume Next
wsSummary.PivotTables("PivotTable3").TableRange2.Clear
On Error GoTo 0
' 1) Create the PivotCache
Set pc = wb.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=rngSource, _
Version:=xlPivotTableVersion14)
' 2) Create the PivotTable from that cache
Set pt = pc.CreatePivotTable( _
TableDestination:=wsSummary.Range("A3"), _
TableName:="PivotTable3", _
DefaultVersion:=xlPivotTableVersion14)
' (Optional) select the top-left cell of the new pivot
wsSummary.Activate
wsSummary.Range("A3").Select
End Sub
Leina,
Thank you very much for this, much appreciated.
I have taken your code and coded the remainder of my macro with your directions and it works perfectly.
I have saved your macro to a separate file that I can have for future use.
Thanks again.