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 techguruplus telegram group Join Our WhatsApp Group techguruplus whatsapp group
Nazim Khan - Author Image

Nazim Khan (Author) 📞 +91 9536250020
[MBA in Finance]

Nazim Khan is an expert in Microsoft Excel. He teaches people how to use it better. He has been doing this for more than ten years. He is running this website (TechGuruPlus.com) and a YouTube channel called "Business Excel" since 2016. He shares useful tips from his own experiences to help others improve their Excel skills and careers.

Leave a Comment