Amazon VBA Bedienungsanleitung

Stöbern Sie online oder laden Sie Bedienungsanleitung nach Software Amazon VBA herunter. Using VBA to Create Pivot Tables Benutzerhandbuch

  • Herunterladen
  • Zu meinen Handbüchern hinzufügen
  • Drucken
  • Seite
    / 60
  • Inhaltsverzeichnis
  • LESEZEICHEN
  • Bewertet. / 5. Basierend auf Kundenbewertungen
Seitenansicht 0
IN THIS CHAPTER
Using VBA to Create Pivot
Tables
11
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-
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.
Introducing VBA . . . . . . . . . . . . . . . . . . . . . . . .231
Learning Tricks of the Trade . . . . . . . . . . . . . .234
Understanding Versions . . . . . . . . . . . . . . . . .236
Building a Pivot Table in Excel VBA . . . . . . . .239
Creating a Report Showing Revenue
by Product . . . . . . . . . . . . . . . . . . . . . . . . . . . .246
Handling Additional Annoyances When
Creating Your Final Report . . . . . . . . . . . . . . .250
Addressing Issues with Two or More
Data Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . .257
Summarizing Date Fields with Grouping . . .263
Using Advanced Pivot Table Techniques . . . .267
Controlling the Sort Order Manually . . . . . . .276
Using Sum, Average, Count, Min,Max,
and More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .276
Creating Report Percentages . . . . . . . . . . . . .277
Using New Pivot Table Features in
Excel 2007 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .279
Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . .289
12_0789736012_CH11.qxd 12/11/06 6:26 PM Page 231
Seitenansicht 0
1 2 3 4 5 6 ... 59 60

Inhaltsverzeichnis

Seite 1 - Using VBA to Create Pivot

IN THIS CHAPTERUsing VBA to Create PivotTables11Introducing VBAVersion 5 of Excel introduced a powerful newmacro language called Visual Basic for Appl

Seite 2 - Visual Basic Editor

Chapter 11 Using VBA to Create Pivot Tables24011In Excel 2000 and newer, you first build a pivot cache object to describe the input area ofthe data:D

Seite 3 - Visual Basic Tools

241Building a Pivot Table in Excel VBAYou can now run through the steps needed to lay out the pivot table. In the .AddFieldsmethod, you can specify on

Seite 4 - Learning Tricks of the Trade

‘ Set up the data fieldsWith PT.PivotFields(“Revenue”).Orientation = xlDataField.Function = xlSum.Position = 1End WithAt this point, you’ve given VBA

Seite 5

243Building a Pivot Table in Excel VBASet PRange = WSD.Cells(1, 1).Resize(FinalRow, FinalCol)Set PTCache = ActiveWorkbook.PivotCaches.Add(SourceType:=

Seite 6 - Understanding Versions

Determining Size of a Finished Pivot TableKnowing the size of a pivot table in advance is difficult. If you run a report of transactionaldata on one d

Seite 7 - New in Excel 2007

245Building a Pivot Table in Excel VBADim PT As PivotTableDim PRange As RangeDim FinalRow As LongSet WSD = Worksheets(“PivotTable”)‘ Delete any prior

Seite 8 - Table 11.2 Continued

WSD.ActivateRange(“R1”).SelectEnd SubThe preceding code creates the pivot table. It then copies the results as values and pastesthem as values in R10:

Seite 9 - Property Description

247Creating a Report Showing Revenue by ProductHere are just a few of the annoyances that most pivot tables present in their default state: The Outli

Seite 10

Ensuring Table Layout Is UtilizedIn previous versions of Excel, multiple row fields appeared in multiple columns. Three lay-outs are now available. Th

Seite 11 - Figure 11.3

249Creating a Report Showing Revenue by ProductWhen you have large numbers, displaying the thousands separator helps the person readingthe report. To

Seite 12 - Figure 11.4

 Enable all macros (not recommended; potentially dangerous code can run)—this settingis equivalent to low macros security in Excel 2003. Because it c

Seite 13 - Figure 11.5

A different technique is to turn on the first subtotal. This method automatically turns offthe other 11 subtotals. You can then turn off the first sub

Seite 14 - Figure 11.6

251Handling Additional Annoyances When Creating Your Final Reportvariables to the original workbook, new workbook, and first worksheet in the new work

Seite 15

Note that you use the Paste Special option to paste just values and number formats. Thisgets rid of both borders and the pivot nature of the table. Yo

Seite 16 - Listing 11.2 Continued

253Handling Additional Annoyances When Creating Your Final Report‘ Do some basic formatting‘ Autofit columns, bold the headings, right-alignSelection.

Seite 17 - Figure 11.8

Dim TotColumns()Dim I as IntegerFinalCol = Cells(3, Columns.Count).End(xlToLeft).ColumnReDim Preserve TotColumns(1 To FinalCol - 2)For i = 3 To FinalC

Seite 18

255Handling Additional Annoyances When Creating Your Final Report‘ Create the Pivot Table from the Pivot CacheSet PT = PTCache.CreatePivotTable(TableD

Seite 19

.Font.Size = 14End With‘ Copy the Pivot Table data to row 3 of the Report sheet‘ Use Offset to eliminate the title row of the pivot tablePT.TableRange

Seite 20 - Figure 11.9

257Addressing Issues with Two or More Data Fields11Figure 11.11Converting 50,000 rowsof transactional data tothis useful report takesless than two sec

Seite 21 - In Excel 2000 and earlier

With PT.PivotFields(“Units”).Orientation = xlDataField.Function = xlSum.Position = 2.NumberFormat = “#,##0”End WithChapter 11 Using VBA to Create Piv

Seite 22 - Handling Final Formatting

259Addressing Issues with Two or More Data Fieldsalways done at the summary level. If you define a calculated field for average price asRevenue divide

Seite 23 - Adding Subtotals

233Introducing VBA11Figure 11.2The Visual Basic Editorwindow is lurkingbehind every copy ofExcel shipped since 1993.Project ExplorerProperties windowC

Seite 24 - Putting It All Together

‘ Set up the row fieldsPT.AddFields RowFields:=”Product”, ColumnFields:=”Data”‘ Define Calculated FieldsPT.CalculatedFields.Add Name:=”AveragePrice”,

Seite 25

261Addressing Issues with Two or More Data Fields11Figure 11.14The virtual Data dimen-sion contains two fieldsfrom your dataset plus acalculation.It i

Seite 26 - Listing 11.3 Continued

‘ Define input area and set up a Pivot CacheFinalRow = WSD.Cells(Rows.Count, 1).End(xlUp).RowFinalCol = WSD.Cells(1, Columns.Count). _End(xlToLeft).Co

Seite 27 - Figure 11.11

263Summarizing Date Fields with Grouping11Figure 11.16After the componentsthat make up the calcu-lated Plants Group itemare hidden,the total rev-enue

Seite 28 - Calculated Data Fields

Creating a group with VBA is a bit quirky. The .Group method can be applied to only a sin-gle cell in the pivot table, and that cell must contain a da

Seite 29

265Summarizing Date Fields with Grouping‘ Set up the row fieldsPT.AddFields RowFields:=”InvoiceDate”, ColumnFields:=”Region”‘ Set up the data fieldsWi

Seite 30 - Calculated Items

Listing 11.7 Code That Uses the Group Feature to Roll Daily Dates Up to Weekly DatesSub ReportByWeek()‘ Listing 11.7Dim WSD As WorksheetDim PTCache As

Seite 31 - Figure 11.14

267Using Advanced Pivot Table Techniques‘ Ensure that we get zeros instead of blanks in the data areaPT.NullString = “0”‘ Calc the pivot table to allo

Seite 32 - Listing 11.5 Continued

Listing 11.8 Code Used to Create the Top 5 Markets ReportSub Top5Markets()‘ Listing 11.8‘ Produce a report of the top 5 marketsDim WSD As WorksheetDim

Seite 33 - Figure 11.15

269Using Advanced Pivot Table Techniques.Position = 1.NumberFormat = “#,##0”.Name = “Total Revenue”End With‘ Ensure that we get zeros instead of blank

Seite 34 - Figure 11.17

 Despite the aforementioned error checking, Excel may still encounter an error at run-time. If this happens, click the Debug button. The line that ca

Seite 35 - Group by Week

The Top 5 Markets report actually contains two snapshots of a pivot table. After using theAutoShow feature to grab the top five markets with their tot

Seite 36 - Figure 11.18

271Using Advanced Pivot Table Techniques‘ Delete any prior pivot tablesFor Each PT In WSD.PivotTablesPT.TableRange2.ClearNext PTWSD.Range(“R1:AZ1”).En

Seite 37

MsgBox “Detail reports for top 3 customers have been created.”End SubCreating Reports for Each Region or ModelA pivot table can have one or more Repor

Seite 38 - Figure 11.19

273Using Advanced Pivot Table TechniquesPT.TableRange2.Offset(3, 0)PT.TableRange1.Offset(1, 0)Which you use is your preference, but if you use TableRa

Seite 39

‘ Turn off updating while building the tablePT.ManualUpdate = True‘ Set up the row fieldsPT.AddFields RowFields:=”Customer”, ColumnFields:=”Data”, _Pa

Seite 40 - Figure 11.20

275Using Advanced Pivot Table TechniquesWSR.Cells(LastRow, 1).Value = “Top 5 Total”‘ Do some basic formatting‘ Autofit columns, bold the headings, rig

Seite 41

PivItem.Visible = TrueCase ElsePivItem.Visible = FalseEnd SelectNext PivItemControlling the Sort Order ManuallyIf your company has been reporting regi

Seite 42 - Listing 11.9 Continued

277Creating Report Percentages.Function = xlAverage.Position = 3.NumberFormat = “#,##0”.Name = “Average Revenue”End WithWith PT.PivotFields(“Revenue”)

Seite 43 - Figure 11.21

Percentage Growth from Previous MonthWith ship months going down the columns, you might want to see the percentage of rev-enue growth from month to mo

Seite 44 - Listing 11.10 Continued

279Using New Pivot Table Features in Excel 2007Figure 11.22 shows the results of a pivot table with three custom calculation settings, as dis-cussed e

Seite 45

235Learning Tricks of the TradeWriting Code to Handle Any Size Data RangeThe macro recorder hard-codes the fact that your data is in a range, such as

Seite 46

To clear the filter from the Branch field, use the ClearAllFilters method:PT.PivotFields(“Branch”).ClearAllFiltersTo apply a date filter to the invoic

Seite 47 - Creating Report Percentages

281Using New Pivot Table Features in Excel 2007PT.PivotFields(“Branch”).PivotFilters.Add _Type:=xlValueIsBetween, _DataField:=PT.PivotFields(“Sum of R

Seite 48 - Running Total

xlCaptionContains Filters for all captions that contain the specifiedstringxlCaptionDoesNotBeginWith Filters for all captions that do not begin withth

Seite 49 - Using the New Filters

283Using New Pivot Table Features in Excel 2007xlDateNextMonth Filters for all dates that apply to the next monthxlDateNextQuarter Filters for all dat

Seite 50 - Figure 11.23

xlValueIsNotBetween Filters for all values that are not between a specified range of valuesxlYearToDate Filters for all values that are within one yea

Seite 51 - Table 11.3 Filter Types

285Using New Pivot Table Features in Excel 2007Changing the LayoutThe Layout group of the Design ribbon contains four drop-downs. These drop-downs con

Seite 52 - Table 11.3 Continued

PT.RowAxisLayout xlTabularRowPT.RowAxisLayout xlOutlineRowPT.RowAxisLayout = xlCompactRowIn Excel 2007, you can add a blank line to the layout after e

Seite 53 - Filter Type Description

287Using New Pivot Table Features in Excel 2007‘ Delete any prior pivot tablesFor Each PT In WSD.PivotTablesPT.TableRange2.ClearNext PTWSD.Range(“R1:A

Seite 54 - Applying a Table Style

Understanding Special Considerations for Excel 97Pivot tables and VBA took a radical turn in Excel 2000. In Excel 2000, Microsoft introducedthe PivotC

Seite 55 - Changing the Layout

289Next StepsNext StepsIn the next chapter, you learn a myriad of techniques for handling common questions andissues with pivot tables.1112_0789736012

Seite 56 - Applying a Data Visualization

End+Down Versus End+UpYou might be tempted to find the final row by starting in cell A1 and using the End key in conjunction with the down-arrow key.

Seite 57

12_0789736012_CH11.qxd 12/11/06 6:26 PM Page 290

Seite 58

237Understanding VersionsNew in Excel 2007Although the basic concept of pivot tables is the same in Excel 2007 as it was in Excel 2003,several new fea

Seite 59 - Next Steps

AllowMultipleFilters Indicates whether a pivot field can have multiplefilters applied to it at the same time.CompactLayoutColumnHeader Specifies the

Seite 60

239Building a Pivot Table in Excel VBAShowDrillIndicators Specifies whether drill indicators are shown inthe pivot table.ShowTableStyleColumnHeaders

Kommentare zu diesen Handbüchern

Keine Kommentare