ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

VBA: Pivot Table Automation from Multiple Sources

VBA (Visual Basic for Applications)

Goal -- WPM

Ready
Exercise Algorithm Area
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
Algorithm description viewbox

VBA: Pivot Table Automation from Multiple Sources

Algorithm description:

This VBA macro automates the creation and configuration of an Excel PivotTable. It takes source and summary sheet names, a desired PivotTable name, and field names as input. It dynamically determines the data range, creates a PivotCache, builds the PivotTable, and assigns specified fields to rows, columns, and values, using a chosen aggregation function. This is a powerful tool for generating dynamic reports and summaries from raw data.

Algorithm explanation:

The `AutomatePivotTable` subroutine is designed to streamline PivotTable creation. It begins by validating the existence of the `sourceSheetName` and creates the `summarySheetName` if it doesn't exist. It then dynamically determines the `dataRange` from the source sheet, ensuring there's data present. A `PivotCache` is created using the determined `sourceData`. Subsequently, a new `PivotTable` is created on the `summarySheetName` using the `PivotCache`. The core configuration involves accessing `PivotFields` by their names and assigning them to `xlRowField`, `xlColumnField`, or `xlDataField` orientations, along with their `Position` and `Function` (e.g., `xlSum`, `xlCount`). Error handling is implemented using `On Error GoTo ErrorHandler` to catch issues like missing sheets, insufficient data, or invalid field names. `Application.ScreenUpdating` and `Application.Calculation` are managed to optimize performance. The time complexity is dependent on the size of the data range and the complexity of the PivotTable configuration, but the macro itself is efficient. Space complexity is primarily for the PivotCache and the PivotTable object. Edge cases handled include missing sheets, empty data, and potentially invalid field names (which would raise an error).

Pseudocode:

SUB AutomatePivotTable(sourceSheetName, summarySheetName, pivotTableName, dataFieldName, rowFieldName, colFieldName, valueFieldName, aggregationType)
  GET wsSource
  IF wsSource not found THEN RAISE error

  GET wsSummary, OR CREATE it if not found

  DETERMINE dataRange from wsSource (lastRow, lastCol)
  IF dataRange is empty THEN RAISE error
  sourceDataString = Format(sourceSheetName, dataRange)

  SET pivotDestination = wsSummary.Cells(1, 1)

  DISABLE screen updating, set calculation to manual

  DELETE existing PivotTable named pivotTableName on wsSummary (if exists)

  CREATE PivotCache using sourceDataString
  CREATE PivotTable on pivotDestination with pivotTableName using PivotCache

  GET pivotField for rowFieldName
  SET orientation = xlRowField, position = 1

  GET pivotField for colFieldName
  SET orientation = xlColumnField, position = 1

  GET pivotField for valueFieldName
  SET orientation = xlDataField, function = aggregationType, position = 1

  ENABLE screen updating, set calculation to automatic
  DISPLAY success message

ERROR HANDLER:
  ENABLE screen updating, set calculation to automatic
  DISPLAY error message
END SUB