VBA Code to Create a Pivot Table with Dynamic Range in Excel

VBA Code:

Sub CreateDynamicPivotTable()
    Dim sourceData As Range
    Dim pivotTable As PivotTable
    Dim pivotCache As PivotCache
    Dim pivotWorksheet As Worksheet
    
    ' Set the source data range for the pivot table
    Set sourceData = Worksheets("Sheet1").Range("A1:C100") ' Change the sheet name and range as desired
    
    ' Create a new pivot cache
    Set pivotCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=sourceData)
    
    ' Create a new worksheet for the pivot table
    Set pivotWorksheet = ThisWorkbook.Worksheets.Add
    
    ' Create a new pivot table on the pivot worksheet
    Set pivotTable = pivotWorksheet.PivotTables.Add(PivotCache:=pivotCache, TableDestination:=pivotWorksheet.Range("A1"))
    
    ' Specify the pivot table fields and settings
    With pivotTable
        .RowFields.Add DataField:=pivotTable.PivotFields("Category")
        .ColumnFields.Add DataField:=pivotTable.PivotFields("Month")
        .AddDataField pivotTable.PivotFields("Amount"), "Sum of Amount", xlSum
    End With
    
    ' Format the pivot table as desired
    
    ' Autofit columns
    pivotWorksheet.UsedRange.Columns.AutoFit
    
    ' Apply a pivot table style
    pivotTable.TableStyle2 = "PivotStyleMedium9"
    
    ' Inform the user that the pivot table has been created
    MsgBox "The pivot table has been created on a new worksheet."
End Sub

Check All VBA Codes

Join Our Telegram Group

Join the TechGuruPlus Telegram group

Join Our WhatsApp Group

Join the TechGuruPlus WhatsApp group
Nazim Khan, founder of TechGuruPlus.com

— Founder & Editor, TechGuruPlus.com
[MBA in Finance]

Nazim Khan has spent over ten years working with Excel, Tally and office documentation in accounts, finance and MIS roles. He has been running TechGuruPlus.com since 2016, where he publishes free editable templates for office work, and the YouTube channel Business Excel. He has trained more than 50,000 people online. Every template on this site is built and checked by him before it is published.

Contact  Â·  Excel Course

Leave a Comment