Amazon VBA Manual
Amazon VBA Manual

Amazon VBA Manual

Using vba to create pivot tables

Advertisement

Quick Links

Using VBA to Create Pivot
Tables
Introducing VBA
Version 5 of Excel introduced a powerful new
macro language called Visual Basic for Applications
(VBA). Every copy of Excel shipped since 1993 has
had a copy of the powerful VBA language hiding
behind the worksheets. VBA allows you to perform
steps that you normally perform in Excel, but to
perform them very very quickly and flawlessly. I've
seen a VBA program take a process that would take
days each month and turn it into a single button
click and a minute of processing time.
Don't be intimidated by VBA. The VBA macro
recorder tool will get you 90% of the way to a use-
ful macro and I will get you the rest of the way
there using examples in this chapter.
Every example in this chapter is available for down-
load from http://www.mrexcel.com/
pivot2007data.html/.
Enabling VBA in Your Copy of Excel
By default, VBA is disabled in Office 2007. Before
you can start using VBA, you need to enable
macros in the Trust Center. From the Office icon
menu, choose Excel Options, Trust Center, Trust
Center Settings, Macro Settings.
Choose one of the options below.
Disable all macros with notification-this set-
I
ting is equivalent to medium macro security in
Excel 2003. When you open a workbook that
contains macros, a message will appear alerting
that there are macros in the workbook. If you
expect macros to be in the workbook, you sim-
ply click Options, Enable to allow the macros
to run. This is the safest setting, as it forces
you to explicitly enable macros in each work-
book.
11
I N T H I S C H A P T E R
Introducing VBA . . . . . . . . . . . . . . . . . . . . . . . .231
Learning Tricks of the Trade . . . . . . . . . . . . . .234
Understanding Versions . . . . . . . . . . . . . . . . .236
by Product . . . . . . . . . . . . . . . . . . . . . . . . . . . .246
Creating Your Final Report . . . . . . . . . . . . . . .250
Data Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . .257
and More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .276
Creating Report Percentages . . . . . . . . . . . . .277
Excel 2007 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .279
Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . .289

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the VBA and is the answer not in the manual?

Questions and answers

Subscribe to Our Youtube Channel

Summary of Contents for Amazon VBA

  • Page 1: Table Of Contents

    VBA allows you to perform Introducing VBA ......231 steps that you normally perform in Excel, but to Learning Tricks of the Trade .
  • Page 2 .xlsm Enabling the Developer Ribbon Most of the VBA tools are located on a Developer tab of the Excel 2007 Ribbon. By default, this tab is not displayed. To enable it, from the Office icon menu, select Excel Options, Popular. Then choose Show Developer Tab in the Ribbon.
  • Page 3: Introducing Vba

    Visual Basic Tools Visual Basic is a powerful development environment. Although this chapter cannot offer a complete course on VBA, if you are new to VBA, you should take advantage of these impor- tant tools: As you begin to type code, Excel may offer a drop-down with valid choices. This fea- ture, known as AutoComplete, allows you to type code faster and eliminate typing mis- takes.
  • Page 4: Learning Tricks Of The Trade

    When you are in Debug mode, use the Debug menu to step line by line through code. You can toggle back and forth between Excel and VBA to see the effect of running a line of code on the worksheet.
  • Page 5 There is nothing magic about the variable name . You could call this variable FinalRow , or even your dog’s name. However, because VBA allows you to use meaningful variable names, you should use something such as to describe the final row.
  • Page 6: Understanding Versions

    4, but the cell also has a font size, a font color, a row, a column, possibly a for- mula, possibly a comment, a list of precedents, and more. It is possible in VBA to create a super-variable that contains all the information about a cell or about any object.
  • Page 7 Every new feature adds one or more methods or properties to VBA. If you are hoping to share your pivot table macro with people running prior versions of Excel, you need to avoid these methods.
  • Page 8 Chapter 11 Using VBA to Create Pivot Tables Table 11.2 Continued Property Description Indicates whether a pivot field can have multiple AllowMultipleFilters filters applied to it at the same time. Specifies the caption that is displayed in the col- CompactLayoutColumnHeader umn header of a pivot table when in compact row layout form.
  • Page 9: Building A Pivot Table In Excel Vba

    Building a Pivot Table in Excel VBA In this chapter, we do not mean to imply that you use VBA to build pivot tables to give to your clients. Rather, the purpose of this chapter is to remind you that pivot tables can be used as a means to an end;...
  • Page 10 C A U T I O N Although the Excel user interface has new names for the various sections of a pivot table,VBA code will continue to refer to the old names. Microsoft had to use this choice, otherwise millions of lines of code would stop working in Excel 2007 when they referred to a page field instead of a filter field.
  • Page 11 Count of Revenue button and change it to Sum of Revenue. In VBA, you should always explicitly define that you are creating a sum of revenue by explicitly setting the...
  • Page 12 .Orientation = xlDataField .Function = xlSum .Position = 1 End With At this point, you’ve given VBA all the settings required to correctly generate the pivot table. If you set , Excel calculates and draws the pivot table. You can ManualUpdate...
  • Page 13 Building a Pivot Table in Excel VBA Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol) Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:= _ xlDatabase, SourceData:=PRange) ‘ Create the Pivot Table from the Pivot Cache Set PT = PTCache.CreatePivotTable(TableDestination:=WSD. _ Cells(2, FinalCol + 2), TableName:=”PivotTable1”) ‘ Turn off updating while building the table PT.ManualUpdate = True...
  • Page 14 Chapter 11 Using VBA to Create Pivot Tables Determining Size of a Finished Pivot Table Knowing the size of a pivot table in advance is difficult. If you run a report of transactional data on one day, you may or may not have sales from the West region, for example. This could cause your table to be either six or seven columns wide.
  • Page 15 Building a Pivot Table in Excel VBA Dim PT As PivotTable Dim PRange As Range Dim FinalRow As Long Set WSD = Worksheets(“PivotTable”) ‘ Delete any prior pivot tables For Each PT In WSD.PivotTables PT.TableRange2.Clear Next PT WSD.Range(“R1:AZ1”).EntireColumn.Clear ‘ Define input area and set up a Pivot Cache FinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).Row...
  • Page 16: Creating A Report Showing Revenue By Product

    Chapter 11 Using VBA to Create Pivot Tables Listing 11.2 Continued WSD.Activate Range(“R1”).Select End Sub The preceding code creates the pivot table. It then copies the results as values and pastes them as values in R10:V13. Figure 11.6 shows an intermediate result just before the original pivot table is cleared.
  • Page 17 Creating a Report Showing Revenue by Product Figure 11.8 Use the power of the pivot table to get the summarized data, but then use your own com- mon sense in formatting the report. Here are just a few of the annoyances that most pivot tables present in their default state: The Outline view is horrible.
  • Page 18 Controlling the Sort Order with AutoSort The Excel user interface offers an AutoSort option that enables you to show markets in descending order based on revenue. The equivalent code in VBA to sort the product field by descending revenue uses the...
  • Page 19 Alternatively, you can surround the character with double quotation marks. To put double quotation marks inside a quoted string in VBA, you must put two sequential quotation marks. To set up a format in tenths of millions that uses the format, you #,##0.0,,”MM”...
  • Page 20: Handling Additional Annoyances When Creating Your Final Report

    Suppressing Grand Total for Rows Because you are going to be using VBA code to add automatic subtotals, you can get rid of the Grand Total row. If you turn off Grand Total for Rows, you delete the column called Grand Total.
  • Page 21 Handling Additional Annoyances When Creating Your Final Report variables to the original workbook, new workbook, and first worksheet in the new work- book. At the top of the procedure, add these statements: Dim WSR As Worksheet Dim WBO As Workbook Dim WBN As Workbook Set WBO = ActiveWorkbook Set WSD = Worksheets(“Pivot Table”)
  • Page 22 Copy the formulas in column A and convert them to values by choosing Home, Clipboard, Paste, Paste Values. Fixing the Outline view in VBA requires fewer steps. The equivalent VBA logic is shown here: Find the last row of the report.
  • Page 23 Handling Additional Annoyances When Creating Your Final Report ‘ Do some basic formatting ‘ Autofit columns, bold the headings, right-align Selection.Columns.AutoFit Range(“A3”).EntireRow.Font.Bold = True Range(“A3”).EntireRow.HorizontalAlignment = xlRight Range(“A3:B3”).HorizontalAlignment = xlLeft ‘ Repeat rows 1-3 at the top of each page WSR.PageSetup.PrintTitleRows = “$1:$3”...
  • Page 24: Putting It All Together

    Chapter 11 Using VBA to Create Pivot Tables Dim TotColumns() Dim I as Integer FinalCol = Cells(3, Columns.Count).End(xlToLeft).Column ReDim Preserve TotColumns(1 To FinalCol - 2) For i = 3 To FinalCol TotColumns(i - 2) = i Next i Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=TotColumns,_...
  • Page 25 Handling Additional Annoyances When Creating Your Final Report ‘ Create the Pivot Table from the Pivot Cache Set PT = PTCache.CreatePivotTable(TableDestination:=WSD. _ Cells(2, FinalCol + 2), TableName:=”PivotTable1”) ‘ Turn off updating while building the table PT.ManualUpdate = True ‘ Set up the row fields PT.AddFields RowFields:=Array(“Product”, “Market”), _ ColumnFields:=”InvoiceDate”...
  • Page 26 Chapter 11 Using VBA to Create Pivot Tables Listing 11.3 Continued .Font.Size = 14 End With ‘ Copy the Pivot Table data to row 3 of the Report sheet ‘ Use Offset to eliminate the title row of the pivot table PT.TableRange2.Offset(1, 0).Copy...
  • Page 27: Addressing Issues With Two Or More Data Fields

    It is often preferable to have the data field as the outermost row field. When a pivot table is going to have more than one data field, you have a virtual field named Σ Values in the drop zones of the PivotTable Field List. In VBA, this equivalent virtual field is named Data.
  • Page 28 Chapter 11 Using VBA to Create Pivot Tables With PT.PivotFields(“Units”) .Orientation = xlDataField .Function = xlSum .Position = 2 .NumberFormat = “#,##0” End With Figure 11.12 The default pivot table report has multiple data fields as the innermost column field.
  • Page 29 Addressing Issues with Two or More Data Fields always done at the summary level. If you define a calculated field for average price as Revenue divided by Units Sold, Excel first adds the total revenue and total quantity, and then it does the division of these totals to get the result. In many cases, this is exactly what you need.
  • Page 30 Chapter 11 Using VBA to Create Pivot Tables Listing 11.4 Continued ‘ Set up the row fields PT.AddFields RowFields:=”Product”, ColumnFields:=”Data” ‘ Define Calculated Fields PT.CalculatedFields.Add Name:=”AveragePrice”, Formula:=”=Revenue/Units” ‘ Set up the data fields With PT.PivotFields(“Revenue”) .Orientation = xlDataField .Function = xlSum .Position = 1...
  • Page 31 Addressing Issues with Two or More Data Fields Figure 11.14 The virtual Data dimen- sion contains two fields from your dataset plus a calculation. It is shown along the column area of the report. Listing 11.5 Code That Adds a New Item Along the Product Dimension Sub CalcItemsProblem() ‘...
  • Page 32 Chapter 11 Using VBA to Create Pivot Tables Listing 11.5 Continued ‘ Define input area and set up a Pivot Cache FinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).Row FinalCol = WSD.Cells(1, Columns.Count). _ End(xlToLeft).Column Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol) Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:= _ xlDatabase, SourceData:=PRange.Address)
  • Page 33: Summarizing Date Fields With Grouping

    Summarizing Date Fields with Grouping Figure 11.15 Unless you love restating numbers to the Securities and Exchange Commission, avoid using calculated items. Look closely at the results shown in Figure 11.15. The calculation for Plants Group is cor- rect. The approximate $2.3 million for the Plants Group is the sum of $1.1 million of land- scaping and $1.2 million of Green Plants.
  • Page 34 .Group gle cell in the pivot table, and that cell must contain a date or the Date field label. This is the first example in this chapter where you must allow VBA to calculate an intermediate pivot table result. You must define a pivot table with Invoice Date in the row field. Turn off to allow the Date field to be drawn.
  • Page 35 Summarizing Date Fields with Grouping ‘ Set up the row fields PT.AddFields RowFields:=”InvoiceDate”, ColumnFields:=”Region” ‘ Set up the data fields With PT.PivotFields(“Revenue”) .Orientation = xlDataField .Function = xlSum .Position = 1 .NumberFormat = “#,##0” End With ‘ Ensure that we get zeros instead of blanks in the data area PT.NullString = “0”...
  • Page 36 Chapter 11 Using VBA to Create Pivot Tables Figure 11.18 Use the Number of Days setting to group by week. Listing 11.7 Code That Uses the Group Feature to Roll Daily Dates Up to Weekly Dates Sub ReportByWeek() ‘ Listing 11.7...
  • Page 37: Using Advanced Pivot Table Techniques

    As with the AutoSort option, you could be a pivot table pro and never have stumbled across the AutoShow feature in Excel. This setting lets you select either the top or bottom n records based on any data field in the report. The code to use AutoShow in VBA uses the method: .AutoShow ‘...
  • Page 38 Chapter 11 Using VBA to Create Pivot Tables Figure 11.19 The Top 5 Markets report contains two pivot tables. Listing 11.8 Code Used to Create the Top 5 Markets Report Sub Top5Markets() ‘ Listing 11.8 ‘ Produce a report of the top 5 markets...
  • Page 39 Using Advanced Pivot Table Techniques .Position = 1 .NumberFormat = “#,##0” .Name = “Total Revenue” End With ‘ Ensure that we get zeros instead of blanks in the data area PT.NullString = “0” ‘ Sort markets descending by sum of revenue PT.PivotFields(“Market”).AutoSort Order:=xlDescending, _ Field:=”Total Revenue”...
  • Page 40 Chapter 11 Using VBA to Create Pivot Tables The Top 5 Markets report actually contains two snapshots of a pivot table. After using the AutoShow feature to grab the top five markets with their totals, the macro went back to the pivot table, removed the AutoShow option, and grabbed the total of all markets to produce the Total Company row.
  • Page 41 Using Advanced Pivot Table Techniques ‘ Delete any prior pivot tables For Each PT In WSD.PivotTables PT.TableRange2.Clear Next PT WSD.Range(“R1:AZ1”).EntireColumn.Clear ‘ Define input area and set up a Pivot Cache FinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).Row FinalCol = WSD.Cells(1, Columns.Count). _ End(xlToLeft).Column Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol) Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:= _ xlDatabase, SourceData:=PRange.Address)
  • Page 42 It can serve to filter the report to a certain region, certain model, or certain combination of region and model. In VBA, Report Filter fields are called page fields. To set up a page field in VBA, add the parameter to the method. The...
  • Page 43 Using Advanced Pivot Table Techniques PT.TableRange2.Offset(3, 0) PT.TableRange1.Offset(1, 0) Which you use is your preference, but if you use , you won’t have problems TableRange2 when you try to delete the pivot table with . If you were to acciden- PT.TableRange2.Clear tally attempt to clear when there are page fields, you would end up with the...
  • Page 44 Chapter 11 Using VBA to Create Pivot Tables Listing 11.10 Continued ‘ Turn off updating while building the table PT.ManualUpdate = True ‘ Set up the row fields PT.AddFields RowFields:=”Customer”, ColumnFields:=”Data”, _ PageFields:=”Region” ‘ Set up the data fields With PT.PivotFields(“Revenue”) .Orientation = xlDataField...
  • Page 45 , mak- PivotField PivotItems ing sure to turn them back to visible before the second pass through the loop. This process is easy in VBA. After building the table with in the page field, loop Product through to change the...
  • Page 46: Controlling The Sort Order Manually

    South Enter. As if by magic, North and South switch places. Of course, all the numbers for North move to the appropriate column. The VBA code to do a manual sort involves setting the property for a specific Position . This is somewhat dangerous because you don’t know whether the underlying PivotItem fields will have data for South on any given day.
  • Page 47: Creating Report Percentages

    Creating Report Percentages .Function = xlAverage .Position = 3 .NumberFormat = “#,##0” .Name = “Average Revenue” End With With PT.PivotFields(“Revenue”) .Orientation = xlDataField .Function = xlMin .Position = 4 .NumberFormat = “#,##0” .Name = “Smallest Order” End With With PT.PivotFields(“Revenue”) .Orientation = xlDataField .Function = xlMax .Position = 5...
  • Page 48 Chapter 11 Using VBA to Create Pivot Tables Percentage Growth from Previous Month With ship months going down the columns, you might want to see the percentage of rev- enue growth from month to month. You can set up this arrangement with the setting.
  • Page 49: Using New Pivot Table Features In Excel 2007

    Label Filters, Date Filters, or Value Filters. In Figure 11.23, the flyout menu shows the list of Label filters available for the Branch field. To apply a label filter in VBA, use the method. The following code filters PivotFilters.Add to the Branches that start with 1: PT.PivotFields(“Branch”).PivotFilters.Add _...
  • Page 50 Chapter 11 Using VBA to Create Pivot Tables Figure 11.23 You can easily choose all the Branch items that meet your criteria. To clear the filter from the Branch field, use the method: ClearAllFilters PT.PivotFields(“Branch”).ClearAllFilters To apply a date filter to the invoice date field to find records from this week, use this code: PT.PivotFields(“InvoiceDate”).PivotFilters.Add Type:=xlThisWeek...
  • Page 51 Using New Pivot Table Features in Excel 2007 PT.PivotFields(“Branch”).PivotFilters.Add _ Type:=xlValueIsBetween, _ DataField:=PT.PivotFields(“Sum of Revenue”), _ Value1:=50000, Value2:=100000 Table 11.3 lists all the possible filter types. Table 11.3 Filter Types Filter Type Description Filters for all dates before a specified date xlBefore Filters for all dates on or before a specified date xlBeforeOrEqualTo...
  • Page 52 Chapter 11 Using VBA to Create Pivot Tables Table 11.3 Continued Filter Type Description Filters for all captions that contain the specified xlCaptionContains string Filters for all captions that do not begin with xlCaptionDoesNotBeginWith the specified string Filters for all captions that do not contain the...
  • Page 53 Using New Pivot Table Features in Excel 2007 Filter Type Description Filters for all dates that apply to the next month xlDateNextMonth Filters for all dates that apply to the next quarter xlDateNextQuarter Filters for all dates that apply to the next week xlDateNextWeek Filters for all dates that apply to the next year xlDateNextYear...
  • Page 54 Chapter 11 Using VBA to Create Pivot Tables Table 11.3 Continued Filter Type Description Filters for all values that are not between a xlValueIsNotBetween specified range of values Filters for all values that are within one year of a xlYearToDate...
  • Page 55 Using New Pivot Table Features in Excel 2007 To apply a table style from the gallery, use the property. If you want to get the TableStyle2 correct name, it might be best to record a macro: ‘ Format the pivot table PT.ShowTableStyleRowStripes = True PT.TableStyle2 = “PivotStyleMedium3”...
  • Page 56 Chapter 11 Using VBA to Create Pivot Tables PT.RowAxisLayout xlTabularRow PT.RowAxisLayout xlOutlineRow PT.RowAxisLayout = xlCompactRow In Excel 2007, you can add a blank line to the layout after each group of pivot items. Although the Design ribbon offers a single setting to affect the entire pivot table, the setting is actually applied to each individual pivot field individually.
  • Page 57 Using New Pivot Table Features in Excel 2007 ‘ Delete any prior pivot tables For Each PT In WSD.PivotTables PT.TableRange2.Clear Next PT WSD.Range(“R1:AZ1”).EntireColumn.Clear ‘ Define input area and set up a Pivot Cache FinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).Row FinalCol = WSD.Cells(1, Columns.Count). _ End(xlToLeft).Column Set PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol) Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:= _...
  • Page 58 Using VBA to Create Pivot Tables Understanding Special Considerations for Excel 97 Pivot tables and VBA took a radical turn in Excel 2000. In Excel 2000, Microsoft introduced object. This object allows you to define one pivot cache and then build many PivotCache pivot reports from the pivot cache.
  • Page 59: Next Steps

    Next Steps Next Steps In the next chapter, you learn a myriad of techniques for handling common questions and issues with pivot tables.

Table of Contents