Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a pivot table based on data in a worksheet with VBA
#1
Example:

Sub CreatePivotTable()
    Dim ws As Worksheet
    Dim pt As PivotTable
    Dim ptCache As PivotCache
    Dim ptRange As Range

    'Set the worksheet where the data is located
    Set ws = ThisWorkbook.Sheets("Sheet1")

    'Set the range of data for the pivot table (adjust the range as per your data)
    Set ptRange = ws.Range("A1:B10")

    'Create a new pivot cache based on the data range
    Set ptCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=ptRange)

    'Create a new pivot table on a new worksheet
    Set pt = ptCache.CreatePivotTable(TableDestination:=ws.Cells(1, 4), TableName:="MyPivotTable")
    With pt
        .PivotFields("Category").Orientation = xlRowField
        .AddDataField .PivotFields("Value"), "Sum of Value", xlSum
    End With
End Sub

Explanation:

The code defines a subroutine named CreatePivotTable.
It declares variables for the worksheet (ws), pivot table (pt), pivot cache (ptCache), and the range of data for the pivot table (ptRange).
Set ws = ThisWorkbook.Sheets("Sheet1") specifies the worksheet ("Sheet1") where the data is located.
The ptRange variable is set to the range of data for the pivot table (A1:B10 in this example).
A new pivot cache is created based on the data range using ThisWorkbook.PivotCaches.Create.
The pivot table is created on a new worksheet at cell D1 (TableDestination:=ws.Cells(1, 4)) with the name "MyPivotTable" using ptCache.CreatePivotTable.
The With block is used to customize the pivot table. 
In this example, the "Category" field is set as a row field, and the "Value" field is added as a data field with the aggregation function xlSum.
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Copy data to another worksheet Qomplainerz 0 394 07-27-2023, 11:24 AM
Last Post: Qomplainerz
  Sum values based on criteria Qomplainerz 0 364 07-27-2023, 11:20 AM
Last Post: Qomplainerz
  Create a hyperlink with VBA Qomplainerz 0 404 07-27-2023, 11:10 AM
Last Post: Qomplainerz
  Concatenate data in columns Qomplainerz 0 343 07-27-2023, 11:01 AM
Last Post: Qomplainerz
  Delete rows based on a condition Qomplainerz 0 401 07-27-2023, 09:47 AM
Last Post: Qomplainerz
  Filter data in a worksheet Qomplainerz 0 377 07-27-2023, 09:46 AM
Last Post: Qomplainerz
  Create a chart from data with VBA Qomplainerz 0 375 07-27-2023, 09:44 AM
Last Post: Qomplainerz
  Sort data in a range with VBA Qomplainerz 0 362 07-27-2023, 09:43 AM
Last Post: Qomplainerz
  Insert a new row and fill it with data in VBA Qomplainerz 0 341 07-27-2023, 09:11 AM
Last Post: Qomplainerz
  Add data validation to a cell with VBA Qomplainerz 0 351 07-27-2023, 09:10 AM
Last Post: Qomplainerz

Forum Jump:


Users browsing this thread: 3 Guest(s)