Advertisement
duck__boy1981

VBA to create a Pivot Table

Oct 22nd, 2012
307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Option Explicit
  2.  
  3. '**
  4. ' Call each of the individual Pivot Table creation functions
  5. ''
  6. Function do_pivot_tables()
  7.  
  8.     Debug.Print "    Creating Pivot Table 'MattersByYear' on sheet 'Number of Matters Opened' -" & vbCrLf
  9.     Call do_pivot_matter_by_year
  10.  
  11. End Function
  12.  
  13. '**
  14. ' Set the parameters for and create the "MattersByYear" Pivot Table
  15. ''
  16. Function do_pivot_matter_by_year()
  17.  
  18. Dim pivot_name As Variant           ' The name of the Pivot Table
  19. Dim sheet_name As Variant           ' The name of the sheet that will hold the Pivot Table
  20. Dim sheet_exists As Boolean         ' Whether or not the worksheet for this Pivot Table already exists
  21. Dim row_fields(0) As Variant        ' The row fields for the Pitot Table
  22. Dim column_fields(0) As Variant     ' The column fields for the Pitot Table
  23. Dim data_fields(0, 1) As Variant    ' The data fields for the Pitot Table
  24. Dim filter_fields(2) As Variant     ' The filter fields for the Pitot Table
  25. Dim pivot_title As String           ' The title of the Pivot Table (to display to the user)
  26. Dim pivot_title_range As String     ' The range that should contain to pivot title
  27.    
  28.     ' Set the "Number of Matters Opened" Pivot Table options
  29.    pivot_name = "MattersByYear"
  30.     sheet_name = "Number of Matters Opened"
  31.  
  32.     ' Check to see if the "Number of Matters Opened" Pivot Table already exists, and exit the function if it does not
  33.    Debug.Print "        Checking if the sheet 'Number of Matters Opened' exists -"
  34.     sheet_exists = worksheet_exists("Number of Matters Opened")
  35.     If sheet_exists = True Then
  36.         Debug.Print "            Sheet exists, exiting functions" & vbCrLf
  37.         Exit Function
  38.     Else
  39.         Debug.Print "            Sheet does not exist, creating Pivot Table" & vbCrLf
  40.     End If
  41.    
  42.     ' The row fields
  43.    row_fields(0) = "Fee earner name"
  44.    
  45.     ' The column fields
  46.    column_fields(0) = "Matter open year"
  47.    
  48.     ' The data fields
  49.    data_fields(0, 0) = "Matter code"
  50.     data_fields(0, 1) = "Count"
  51.    
  52.     ' The filter fields
  53.    filter_fields(0) = "Fee earner code"
  54.     filter_fields(1) = "Department code"
  55.     filter_fields(2) = "Work type code"
  56.    
  57.     ' The title
  58.    pivot_title = "Matters Opened per Year by Fee Earner"
  59.     pivot_title_range = "B3:G4"
  60.    
  61.     ' Create the Pivot Table
  62.    Call create_pivot_table(pivot_name, sheet_name, row_fields, column_fields, data_fields, filter_fields, pivot_title, pivot_title_range)
  63.  
  64. End Function
  65.  
  66. '**
  67. ' Creates a Pivot Table using the parameters parsed
  68. '
  69. Function create_pivot_table( _
  70.     pivot_name As Variant, _
  71.     sheet_name As Variant, _
  72.     Optional row_fields As Variant = "", _
  73.     Optional column_fields As Variant = "", _
  74.     Optional data_fields As Variant = "", _
  75.     Optional filter_fields As Variant = "", _
  76.     Optional pivot_title As String = "", _
  77.     Optional pivot_title_range As String = "" _
  78. )
  79.  
  80. Dim position_row As Integer ' The row number to place the new pivot table at
  81. Dim position As String      ' The position of the Pivot Table on the worksheet
  82. Dim source_data As String   ' The source of the data used for the Pivot Table
  83. Dim title_range As Range    ' The Range to be used for the title of the Pivot Table
  84. Dim i As Integer            ' Dummy for looping
  85.  
  86.     ' The source data for the new Pivot Table
  87.    source_data = "v10List"
  88.     position_row = 9 + UBound(filter_fields)
  89.     position = "'" & sheet_name & "'!R" & position_row & "C2"
  90.    
  91.     ' Create a new sheet and rename it
  92.    Debug.Print "        Creating new Sheet for Pivot Table and renaming it - " & sheet_name & vbCrLf
  93.     Sheets.Add
  94.     ActiveSheet.Name = sheet_name
  95.    
  96.     ' Create the Pivot Table
  97.    Debug.Print "        Adding Pivot Table - "
  98.     Debug.Print "            Pivot Table Name - " & pivot_name
  99.     Debug.Print "            Pivot Table Source - " & source_data & vbCrLf
  100.     ActiveWorkbook.PivotCaches.Add( _
  101.         SourceType:=xlDatabase, _
  102.         SourceData:=source_data).CreatePivotTable _
  103.             TableDestination:=position, _
  104.             TableName:=pivot_name, _
  105.             DefaultVersion:=xlPivotTableVersion10
  106.    
  107.     ' Add the row fields
  108.    Debug.Print "        Adding Pivot Rows - "
  109.     For i = 0 To UBound(row_fields) Step 1
  110.         Debug.Print "            Adding Pivot Row - " & row_fields(i)
  111.         With ActiveSheet.PivotTables(pivot_name).PivotFields(row_fields(i))
  112.             .Orientation = xlRowField
  113.             .position = i + 1
  114.         End With
  115.     Next
  116.     Debug.Print "" ' Add a blank line to seperate output in the Immediate window
  117.    
  118.     ' Add the column fields
  119.    Debug.Print "        Adding Pivot Columns - "
  120.     For i = 0 To UBound(column_fields) Step 1
  121.         Debug.Print "            Adding Pivot Column - " & column_fields(i)
  122.         With ActiveSheet.PivotTables(pivot_name).PivotFields(column_fields(i))
  123.             .Orientation = xlColumnField
  124.             .position = i + 1
  125.         End With
  126.     Next
  127.     Debug.Print "" ' Add a blank line to seperate output in the Immediate window
  128.    
  129.     ' Add the data fields
  130.    Debug.Print "        Adding Pivot Data - "
  131.     For i = 0 To UBound(data_fields) Step 1
  132.         Debug.Print "            Adding Pivot Data - " & data_fields(i, 0) & " (" & data_fields(i, 1) & ")"
  133.         ActiveSheet.PivotTables(pivot_name).AddDataField _
  134.         ActiveSheet.PivotTables(pivot_name).PivotFields(data_fields(i, 0)), data_fields(i, 1) & " of " & data_fields(i, 0), xlCount
  135.     Next
  136.     Debug.Print "" ' Add a blank line to seperate output in the Immediate window
  137.    
  138.     ' Add the filter fields
  139.    Debug.Print "        Adding Pivot Filters - "
  140.     For i = 0 To UBound(filter_fields) Step 1
  141.         Debug.Print "            Adding Pivot Filter - " & filter_fields(i)
  142.         With ActiveSheet.PivotTables(pivot_name).PivotFields(filter_fields(i))
  143.             .Orientation = xlPageField
  144.             .position = 1
  145.         End With
  146.     Next
  147.     Debug.Print "" ' Add a blank line to seperate output in the Immediate window
  148.    
  149.     ' Check to see if there is a title for the Pivot Table, and exit if there is not
  150.    Debug.Print "        Checking Pivot Table title existence - "
  151.     If pivot_title = "" Then
  152.         Debug.Print "            No title was set, deleting title rows" & vbCrLf
  153.         ActiveSheet.Range("1:4").EntireRow.Delete
  154.         Exit Function
  155.     Else
  156.         Debug.Print "            Title was set by user - " & pivot_title & vbCrLf
  157.     End If
  158.    
  159.     ' Check to see if a range for the Pivot Table title has been set, and set one if not
  160.    Debug.Print "        Checking Pivot Table title range existence - "
  161.     If pivot_title_range = "" Then
  162.         Debug.Print "            Range was set using default - Range(""B3: E4"")" & vbCrLf
  163.         title_range = ActiveSheet.Range("B3:E4")
  164.     Else
  165.         Debug.Print "            Range was set by user - Range(""" & pivot_title_range & """)" & vbCrLf
  166.         title_range = ActiveSheet.Range(pivot_title_range)
  167.     End If
  168.    
  169.     ' Merge the cells that will contain the Pivot Table title
  170.    Debug.Print "        Merging title range cells" & vbCrLf
  171.     title_range.Select
  172.     With Selection
  173.         .HorizontalAlignment = xlCenter
  174.         .VerticalAlignment = xlBottom
  175.         .WrapText = False
  176.         .Orientation = 0
  177.         .AddIndent = False
  178.         .IndentLevel = 0
  179.         .ShrinkToFit = False
  180.         .ReadingOrder = xlContext
  181.         .MergeCells = False
  182.     End With
  183.     Selection.Merge
  184.    
  185.     ' Format the newly merged cell that will contain the Pivot Table title
  186.    Debug.Print "        Formating title cell" & vbCrLf
  187.     With Selection.Font
  188.         .Bold = True
  189.         .Name = "Arial"
  190.         .Size = 20
  191.         .Strikethrough = False
  192.         .Superscript = False
  193.         .Subscript = False
  194.         .OutlineFont = False
  195.         .Shadow = False
  196.         .Underline = xlUnderlineStyleNone
  197.         .ColorIndex = xlAutomatic
  198.         .TintAndShade = 0
  199.         .ThemeFont = xlThemeFontNone
  200.     End With
  201.    
  202.     ' Add a border to the bottom of the newly merged cell that will contain the Pivot Table title
  203.    Debug.Print "        Adding border to title call" & vbCrLf
  204.     Selection.Borders(xlDiagonalDown).LineStyle = xlNone
  205.     Selection.Borders(xlDiagonalUp).LineStyle = xlNone
  206.     Selection.Borders(xlEdgeLeft).LineStyle = xlNone
  207.     Selection.Borders(xlEdgeTop).LineStyle = xlNone
  208.     With Selection.Borders(xlEdgeBottom)
  209.         .LineStyle = xlContinuous
  210.         .ColorIndex = 0
  211.         .TintAndShade = 0
  212.         .Weight = xlThick
  213.     End With
  214.     Selection.Borders(xlEdgeRight).LineStyle = xlNone
  215.     Selection.Borders(xlInsideVertical).LineStyle = xlNone
  216.     Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
  217.    
  218.     ' Add the title of the Pivot Table to the newly merged cell
  219.    Debug.Print "        Adding title to title call" & vbCrLf
  220.     ActiveCell.Value = pivot_title
  221.    
  222. End Function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement