Forum Discussion

WIllowED's avatar
WIllowED
Copper Contributor
Dec 05, 2025
Solved

Trying to insert Pivot Table

I recorded a new macro, using the tab View Macros-Record Macro, which resulted in the following VBA code:    Sub CreatePivotTable()        Sheets("Year Data").Select        Range("A3:F24").Select ...
  • Leina's avatar
    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").Select

    End Sub

Resources