1Sub AutomatePivotTable(sourceSheetName As String, summarySheetName As String, pivotTableName As String, dataFieldName As String, rowFieldName As String, colFieldName As String, valueFieldName As String, aggregationType As XlConsolidationFunction)
2' Automates the creation and configuration of a PivotTable.
3' Handles multiple data sources (though this example focuses on one).
4' Applies predefined row, column, and value fields.
5' Includes robust error handling.
6
7Dim wsSource As Worksheet
8Dim wsSummary As Worksheet
9Dim ptCache As PivotCache
10Dim pt As PivotTable
11Dim dataRange As Range
12Dim pivotDestination As Range
13Dim sourceData As String
14Dim pivotField As PivotField
15
16' --- Error Handling Setup ---
17On Error GoTo ErrorHandler
18
19' --- Sheet and Range Validation ---
20' Get source worksheet
21On Error Resume Next
22Set wsSource = ThisWorkbook.Sheets(sourceSheetName)
23On Error GoTo ErrorHandler
24If wsSource Is Nothing Then
25Err.Raise vbObjectError + 1001, "AutomatePivotTable", "Source sheet '" & sourceSheetName & "' not found."
26End If
27
28' Get summary worksheet, create if it doesn't exist
29On Error Resume Next
30Set wsSummary = ThisWorkbook.Sheets(summarySheetName)
31On Error GoTo ErrorHandler
32If wsSummary Is Nothing Then
33Set wsSummary = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
34wsSummary.Name = summarySheetName
35End If
36
37' Determine the data range from the source sheet
38Dim lastRow As Long
39Dim lastCol As Long
40lastRow = wsSource.Cells(wsSource.Rows.Count, dataFieldName).End(xlUp).Row
41lastCol = wsSource.Cells(1, wsSource.Columns.Count).End(xlToLeft).Column
42
43If lastRow < 2 Then ' Assuming header row
44Err.Raise vbObjectError + 1002, "AutomatePivotTable", "No data found in source sheet '" & sourceSheetName & "'. PivotTable cannot be created."
45End If
46
47Set dataRange = wsSource.Range(wsSource.Cells(1, 1), wsSource.Cells(lastRow, lastCol))
48sourceData = "'" & sourceSheetName & "'!" & dataRange.Address
49
50' Define the destination for the PivotTable
51Set pivotDestination = wsSummary.Cells(1, 1)
52
53' --- PivotTable Creation ---
54Application.ScreenUpdating = False
55Application.Calculation = xlCalculationManual ' Optimize calculation
56
57' Delete existing PivotTable with the same name if it exists
58On Error Resume Next
59wsSummary.PivotTables(pivotTableName).TableRange2.Clear
60On Error GoTo ErrorHandler
61
62' Create PivotCache
63Set ptCache = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=sourceData, Version:=xlPivotTableVersion15)
64
65' Create PivotTable
66Set pt = ptCache.CreatePivotTable(TableDestination:=pivotDestination, TableName:=pivotTableName, DefaultVersion:=xlPivotTableVersion15)
67
68' --- PivotTable Configuration ---
69
70' Add Row Field
71Set pivotField = pt.PivotFields(rowFieldName)
72pivotField.Orientation = xlRowField
73pivotField.Position = 1
74
75' Add Column Field
76Set pivotField = pt.PivotFields(colFieldName)
77pivotField.Orientation = xlColumnField
78pivotField.Position = 1
79
80' Add Value Field
81Set pivotField = pt.PivotFields(valueFieldName)
82pivotField.Orientation = xlDataField
83pivotField.Function = aggregationType
84pivotField.Position = 1
85' Optional: Set caption for the value field
86' pivotField.Caption = "Sum of " & valueFieldName
87
88' --- Finalization ---
89Application.ScreenUpdating = True
90Application.Calculation = xlCalculationAutomatic
91MsgBox "PivotTable '" & pivotTableName & "' created successfully on sheet '" & summarySheetName & "'.", vbInformation
92Exit Sub
93
94ErrorHandler:
95Application.ScreenUpdating = True
96Application.Calculation = xlCalculationAutomatic
97If Err.Number = vbObjectError + 1001 Or Err.Number = vbObjectError + 1002 Then
98MsgBox Err.Description, vbCritical
99Else
100MsgBox "An unexpected error occurred: " & Err.Description & " (Error " & Err.Number & ")", vbCritical
101End If
102On Error GoTo 0 ' Reset error handling
103
104End Sub