How do I Create Pivot Table With VBA?

Stockbyte/Stockbyte/Getty Images

Creating pivot tables in Excel using Visual Basic for Applications (VBA) can save you time due to your not having to create the tables manually. VBA is a computer programming language used in Microsoft Office applications to automate routine tasks such as creating a pivot table. Don't spend your time creating pivot tables manually if you have many sheets in your workbook; instead create a sub procedure to create them dynamically.

Launch Microsoft Office Excel and type "Customer" in "A1," "Item" in "B1," and "Qty" in "C1." Type "Jon" in "A2," "Jon" in "A3," "Clara" in "A4," "Clara" in "A5," and "Clara" in "A6." Type "soda" in "B2," "beer" in "B3," "soda" in "B4," "water" in "B5," and "beer" in "A6." Type "2" in "C2," "5" in "C3," "10" in "C4," "12" in "C5," and "15" in "C6."

Click the "Developer" tab and click "Visual Basic" to launch the VB Editor. Type the following code to create a new VBA sub procedure:

Private Sub createPivotTable()

Create the variables you will use to create the pivot table by adding the following code:

Define the worksheets you will use:

Determine the row and column count with data:

Define the range for your data:

Create the pivot table in "Sheet2:"

Define the source data for the Pivot table:

Finish your sub by typing "End Sub" in the end of your procedure. Press "F5" to run the procedure and create the pivot table using VBA.

Most recent