Windows IT Pro is the authoritative and independent resource for windows nt, windows 2000, windows 2003, windows xp. Features a collection of resources and magazines for windows IT professionals.
  
  
  Advanced Search 


March 14, 2005

Produce Pivot Tables Programmatically

A new spin on an old favorite
RSS
Subscribe to Windows IT Pro | See More Task Automation Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!

Download the Code Here

For sometime now, I've used Microsoft Excel as my primary VBScript reporting medium. It's easy to sort and organize data in Excel, and in general, Excel is easy to use. I've also found that most people are familiar with it. Team members and managers seem to like Excel because they can easily add their own touches, such as charts and colors, to reports before passing them on to upper management.

Not too long ago, I was manually creating a pivot table that displayed a count of locked-out accounts for an NT domain administration report. I decided to try scripting this functionality. I had tried my hand at scripting pivot tables in the past, but the Microsoft documentation and Visual Basic for Applications (VBA) macros just didn't give me the syntax structure I needed. I had found most of the pieces of this puzzle. I just needed to find the missing few, then put all the pieces together. After an exhaustive trial-and-error period and actually walking away from the project for a couple of months, I decided to give it another shot. It took a couple of long nights, but I finally got all the pieces to fit. The result was two scripts: PivotTable.vbs and PivotTable2.vbs.

PivotTable.vbs creates a pivot table that shows a quarterly breakdown of three roommates and their contributions toward living expenses. PivotTable2.vbs constructs a pivot table for locked-out accounts. It also contains some advanced functionality not included in the first script.

A Look at PivotTable.vbs
Listing 1 shows PivotTable.vbs. The first part of the script sets up the Excel spreadsheet and creates the main worksheet called Quarterly Bills. Note that headers are required in the first row when you create a pivot table.

The code at callout A in Listing 1 builds the sample data to be used in the pivot table. The randomly created test data consists of three roommate names, three types of utilities, the amount paid to the utility, and the quarter the payment was made. Although this example is basic, it paints a clear picture of how you can start producing pivot tables programmatically.

The code at callout B in Listing 1 creates a new worksheet called Summary. The pivot table will reside in this worksheet. The code then selects Quarterly Bills (i.e., the main worksheet that contains the data).

The pivot table creation process begins by calling the PivotTableWizard method, which provides an interface to Excel's PivotTable Wizard. As callout C in Listing 1 shows, I use the method's SourceType argument to specify the type of data source for the pivot table. In this case, I set SourceType to the xlDatabase constant, which specifies the type as an Excel database. There are other constants such as xlExternal (specifies the type as another application) you can use, but this example will concentrate on getting data from the current spreadsheet. Next, I define the range of cells in which the data resides in the Excel database. You have to be precise here. In most cases, the starting point of the range will be A1. The endpoint of the range is the last row and column of data. The column can be hard-coded. In this case, I know that the last column is D because the headers are hard-coded. The code stores the endpoint row in a variable called lastrow. Next, I set the pivot table's destination, which is the Summary worksheet, starting at row 1, column 1. Finally, I provide the name of the database, which is Quarterly Bills.

The lines at callout D in Listing 1 define how the pivot table is constructed. There are three main pieces: row fields, column fields, and data fields. The code uses the Orientation property to define these fields. The Orientation value of 1 specifies a row field, 2 specifies a column field, and 4 specifies a data field. The code also names each field. In this example, the roommates' names and type of utility will appear in the rows labeled Name and Description, respectively. The column containing the quarter the payment was made will appear in a column labeled Quarter. The data field is labeled Amount. Note that the PivotTable Wizard automatically prepends Sum of to Amount, so the data field will appear as Sum of Amount, as Table 1 shows. The PivotTable Wizard also automatically calculates the Grand Total values. In addition, the PivotTable Wizard calculates subtotal values, which the wizard automatically labels as Jack Total, Joe Total, and Judy Total in Table 1.

The two lines after callout D simply close the interface to Excel's PivotTable Wizard. Note that Microsoft Office 2000 doesn't have field-header functionality for pivot tables, so if you're going to use this script with Office 2000 only, you should add the On Error Resume Next statement to the beginning of the script or comment out the line at callout E in Listing 1.

You might want to try switching the Orientation values for the row and column fields to see different layouts for the pivot table. For example, if you change the Orientation value from 1 to 2 in the code

Xl.ActiveSheet.PivotTables _
 ("Quarterly Bills"). _PivotFields _
 ("Description").Orientation = 1

the electricity, telephone, and water data will appear in columns rather than rows. This layout works well if you have only a few unique values for a field. If you have a lot of different values, you'll probably want to list the field as a row; otherwise, you'll have to scroll right to see all the columns in the spreadsheet.

You need to leave the data-field orientation alone. In this example, that would be the code

Xl.ActiveSheet.PivotTables _
 ("Quarterly Bills") _.PivotFields _
 ("Amount").Orientation = 4
   Previous  [1]  2  Next 


Reader Comments
good

downbylhl August 28, 2006 (Article Rating: )


You must log on before posting a comment.

If you don't have a username & password, please register now.




Top Viewed ArticlesView all articles
The Memory-Optimization Hoax

Don't believe the hype. At best, RAM optimizers have no effect. At worst, they seriously degrade performance. ...

Friday at PASS Europe 2006

Kevin talks about the closing day of the event and shares a funny Microsoft film. ...

Escape From Yesterworld

Kevin points you to the funniest SQL Server website ever! ...


Task Automation Whitepapers Essential Guide to E-discovery and Recovery for Microsoft Exchange

Continuous Data Protection and Recovery for Microsoft Exchange

Protecting (You and) Your Data with Exchange Server 2007

Related Events Check out our list of Free Email Newsletters!

Task Automation eBooks Spam Fighting and Email Security for the 21st Century

A Guide to Windows Certification and Public Keys

Keeping Your Business Safe from Attack: Patch Management

Related Task Automation Resources Become a VIP member of the Windows IT Pro community!
Get it all with the VIP CD and VIP access. A $500+ value for only $279!

Subscribe to Windows IT Pro!
Solve your toughest technical problems with our experts and access 10,000 + articles online. 30% off

Monthly Online Pass - Only $5.95!
Get instant access to 10,000+ articles from Windows IT Pro Magazine!

TechNet Virtual Labs
Evaluate and test Microsoft's newest products.

Job Openings in IT


ADS BY GOOGLE SPONSORED LINKS FEATURED LINKS

Maximize your SharePoint Investment – 8 Cities
Discover best practices and tips for both architecting and administering SharePoint. Early Bird Price of $99 through Sept 15th.

Find a new job now on the all new IT Job Hound!
Search jobs, post your resume, and set up job e-mail alerts!

Master SharePoint with 3 eLearning Seminars
Learn how to build a better SharePoint infrastructure and enable powerful collaboration with MVPs Dan Holme and Michael Noel. Register today!

Top Tools for Virtualization Disaster Recovery & Replication
View this web seminar on August 14th to learn about two tools that will result in faster backup and restore with P2V disaster recovery.

SharePointConnections Conference Fall 2008
Don’t miss the premier event for Microsoft IT Professionals in Las Vegas, November 10-13. Register and book your room by August 25 and receive a FREE room night (based on a three night minimum stay).

VMworld 2008 - Sign Up Today!
Join your peers on September 15-18 at The Venetian Hotel in Las Vegas as VMware hosts VMworld 2008, the leading Virtualization event.



Entrust Unified Communications Certs
Secure Exchange 2007 and save 20%. Now through Sept. 2008.

Increase Application Performance
Free White Paper by Editor's Best winner, Texas Memory Systems.

Need to convert between XML, DBs, EDI, and Excel? Try MapForce free!
Drag & drop to transform between popular data formats – get results instantly or generate code.

Microsoft® Tech•Ed EMEA 2008 IT Professionals
Advance your thinking with new ideas and practical real-world solutions at Microsoft’s FIVE day technical infrastructure conference 3-7 Nov., 2008. Register before 26 September 2008 to save €300.

Order Your SQL Fundamentals CD Today!
Learn how to use SQL Server, understand Office integration techniques and dive into the essentials of SQL Express and Visual Basic with this free SQL Fundamentals CD.

Are You Really Compliant with Software Regulations?
View this web seminar that will help you with compliance best practices and check out a management solution to assure that you won’t be in jeopardy of an audit.

Virtualization Congress Oct. 14-16 in London
Don't miss Virtualization Congress, the premiere EMEA conference dedicated to hardware, OS and application virtualization. Oct. 14-16.
Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro Windows Dev Pro IT Job Hound ITTV
IT Library Technical Resources Directory Connected Home Windows Excavator Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 Copyright © 2008 Penton Media, Inc., All rights reserved. Terms and Use | Privacy Statement | Reprints and Licensing