course 209 supplementary materials more excel vba

32
More Excel VBA Course 209 www.LearningTree.com 1 © All rights reserved. Not to be reproduced by any means without prior written consent. Course 209 Supplementary Materials More Excel VBA

Upload: others

Post on 25-Nov-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 1 © All rights reserved. Not to be reproduced by any means without prior written consent.

Course 209 Supplementary Materials

More Excel VBA

Page 2: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 2 © All rights reserved. Not to be reproduced by any means without prior written consent.

Objectives

We will look at VBA and pivot tables VBA in Excel charts

Page 3: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 3 © All rights reserved. Not to be reproduced by any means without prior written consent.

More Excel VBA

Pivot Tables

Charts

Summary

Page 4: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 4 © All rights reserved. Not to be reproduced by any means without prior written consent.

Pivot Tables

The pivot table is one of the most powerful tools in Excel Allows fast analysis of data from different views

Fields can be dragged to different positions Double-clicking on data drills down to base data Fast because data is stored temporarily in cache

Your instructor will now demonstrate use of a pivot table

Page fields Column field

Data field Row field

Page 5: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 5 © All rights reserved. Not to be reproduced by any means without prior written consent.

Pivot Tables (continued)

The Excel object model includes several objects referring to pivot tables

You can use these objects to create and manipulate pivot tables

with VBA Often best to create the pivot table from the UI

Use VBA to manipulate the table afterward – Move and hide fields – Move and hide individual data points

Page 6: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 6 © All rights reserved. Not to be reproduced by any means without prior written consent.

Object Model

Key objects

Workbook

Application

PivotTables collection

Workbooks collection

Worksheet

PivotTable

PivotField

PivotItem

Worksheetscollection

PivotFields collection

PivotItems collection

Range

CommandBar CommandBars

collection

CommandBarControl Controls

collection

Page 7: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 7 © All rights reserved. Not to be reproduced by any means without prior written consent.

Pivot Table Objects

PivotTable Represents one pivot table

PivotField

Represents one of the data fields Orientation property defines position

– xlColumnField, xlDataField, xlHidden, xlPageField, or xlRowField

xlPageField

xlRowField

xlColumnField

xlDataField

Page 8: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 8 © All rights reserved. Not to be reproduced by any means without prior written consent.

Pivot Table Objects (continued)

Separate collections of pivot fields with the same orientation ActiveSheet.PivotTables(1).ColumnField DataFields, HiddenFields, PageFields, RowFields

PivotItem

Represents one data point in a pivot field Used to hide/show points (Visible property) Used to move points (Position property)

Page 9: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 9 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables

The goal of this exercise is to

Use VBA and pivot table objects to manipulate a pivot table

Page 10: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 10 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables

Objective In this exercise, you will learn how to • Manipulate a pivot table with VBA code Overview We will use VBA to create an intuitive user interface for moving pivot fields in a pivot table.

Building the pivot table from the Excel UI

1. Open Excel with an empty workbook.

2. Select the menu option Data | PivotTable and PivotChartReport.

3. Select External data source and click Next.

4. On the next wizard screen, click Get Data. On the following one, select MS Access Databasex and click OK.

5. Select the 209NW.mdb database in the cse209\Input directory and click OK.

This opens a screen where you can select the fields to show in your pivot table.

The 209NW database is an adaptation of the Northwind database, which is supplied as an exercise database with MS Access.

Page 11: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 11 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

6. Expand the tables in the left box and select fields (by clicking

on the right arrow) as follows: Table FieldCategories CategoryName Customers CompanyName

City Country

Order Details Quantity Price

Orders OrderMonth OrderYear

Products ProductName

Click Next when you are ready.

Page 12: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 12 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

7. Click Next on the two following screens (we need no filtering or sorting). On the following screen, select View data or edit query in Microsoft Query and click Finish. Take a moment to view the data and then select File | Return data to Microsoft Excel.

8. Back in Step 2 of 3 of the wizard, you can now see that data fields have been retrieved, so click Next to move on.

9. Choose to locate the pivot table in cell $B$10 in the existing worksheet (just click there), and click Finish.

You are now invited to drop the different pivot fields into the table.

Page 13: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 13 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

10. Drop the OrderYear field into the Column Fields area,

the CategoryName field into the Row Fields area, and the Price field into the Data Items area. Drop all other fields into the Page Fields area.

Page 14: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 14 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

11. The pivot table is ready. Test to move the fields around.

If you lose a field, recover it with the right-most button on the toolbar.

Moving pivot fields takes some experience. We will now build a simpler interface for this task.

Our solution will be to use option buttons to provide a

user form, which lists all the pivot fields and allows us to select orientation (position) for each field.

12. Add a user form with one list box, one command button, one

frame, and five option buttons.

The form should end up as below:

Page 15: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 15 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

13. Set properties as follows:

Object Property Value UserForm1 Name frmPivotTable Caption Select Pivot Fields ShowModal False ListBox1 Name lstFields OptionButton1 Name optPage Caption Page Field OptionButton2 Name optColumn Caption Column Field OptionButton3 Name optRow Caption Row Field OptionButton4 Name optData Caption Data Field OptionButton5 Name optHidden Caption Hidden Field Frame1 Caption Field Orientation CommandButton1 Name cmdClose Caption Close

14. We will be referring to the pivot table quite a lot, so let’s

define a variable for it. This variable must be available throughout the user form, so we must declare it at the top of the code window (module-level).

Dim pvtThisTable as PivotTable

Page 16: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 16 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

15. We should then set it in the user form’s Initialize event.

Set pvtThisTable = ActiveSheet.PivotTables(1)

In the same event, we want to populate the list box with the pivot fields. To sort the list box alphabetically, we will use AddSort.

16. Import the AddSort.bas module to the project and add the following code in the user form’s Initialize event: Dim fldAny As PivotField Set pvtThisTable = ActiveSheet.PivotTables(1) For Each fldAny In pvtThisTable.PivotFields

AddSort lstFields, fldAny.Name Next fldAny lstFields.ListIndex = 0

Page 17: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 17 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

17. Our next task is to move the selected pivot field when the user selects one of the option buttons. Moving a field is effected by changing its Orientation property. The code will be almost the same, whichever option button is clicked, so let’s put it into a general procedure (in the user form) and send the orientation argument together with the procedure call. Let’s name the procedure ChangeFieldLocation. It should change the Orientation property for the field, which is selected in the list box. The code might be: Sub ChangeFieldLocation(intArgument As Integer)

pvtThisTable.PivotFields(lstFields.Value). _

Orientation = intArgument End Sub

18. Each option button can then have the same simple Click

event procedure (but with different arguments); e.g., Private Sub optColumn_Click() ChangeFieldLocation xlColumnField End Sub

19. Insert the same event procedures (with other arguments) for the four other buttons. Refer to the Orientation property in the Help system for the respective intrinsic constant.

Page 18: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 18 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

20. We have not yet implemented the cmdClose button. Add code in its Click event to let it close the form.

Use the generic object Me.

21. Start the user form and test it by moving fields in and out among Hidden, Page fields, Row fields, and Column fields. Do not move Data fields.

Warning! Do not try to move any field that is presently a data field. That is because a data field is really a temporary field with its own name (in our case “Sum of Price”) and we must hide this data field before we can do anything with the Price field.

Page 19: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 19 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

22. Solve the Data field problem by adding code at the beginning of the ChangeFieldLocation procedure. Sub ChangeFieldLocation(intArgument As Integer) On Error Resume Next With pvtThisTable.PivotFields _ ("Sum Of " & lstFields.Value) If .Orientation = xlDataField Then .Orientation = xlHidden End If End With

pvtThisTable.PivotFields(lstFields.Value). _ Orientation = intArgument End Sub

23. Now retest the procedure. It should work also for data fields

this time. Save the workbook as PivotTable.xls.

Congratulations! You have built a UI that simplifies the handling of pivot fields.

Page 20: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 20 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 1: Pivot Tables (continued)

Note that if you click on an option button that is already selected, no Click event occurs. To move two fields after another to the same location, you may have to move the second field somewhere else first. Remedy this problem.

You may want to think about the MouseUp event.

Build an Excel add-in to be used with any pivot table.

Page 21: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 21 © All Rights reserved. Not to be reproduced by any means without prior written consent.

More Excel VBA

Pivot Tables

Charts

Summary

Page 22: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 22 © All Rights reserved. Not to be reproduced by any means without prior written consent.

Object Model

Excel charts can exist in two forms On a separate chart sheet Embedded in a worksheet

This is reflected in the object model

A ChartObject object is an embedded chart The ChartObjects collection represents all embedded charts in a

worksheet The Charts collection represents all chart sheets in a workbook The Chart object represents the chart itself

– Whether embedded or not

It is possible to create a Chart/ChartObject in code In most cases, it is easier to use the Excel interface Use VBA to customize the chart in runtime

Page 23: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 23 © All Rights reserved. Not to be reproduced by any means without prior written consent.

Object Model (continued)

Key objects

WorksheetChart

Series

ChartTitle Legend

Axis

Workbook

Axes collection

ChartObject

Chart

SeriesCollectioncollection

ChartObjects collection

Worksheets collection

Chartscollection

Page 24: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 24 © All Rights reserved. Not to be reproduced by any means without prior written consent.

Events

Key Chart object events BeforeDoubleClick, BeforeRightClick

– Provide four parameters

SeriesChange – User selects another series

A parallel Chart reference is required to trap events from an

embedded chart

ElementID – Which chart element was clickedArg1, Arg2 – Additional information on click point (different information for different ElementIDs) Cancel – Cancel default action

Page 25: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 25 © All Rights reserved. Not to be reproduced by any means without prior written consent.

Using Controls on Charts

ActiveX controls cannot be placed on charts Whether embedded or not

Use controls from the Forms toolbar instead

Use View | Toolbars | Forms

Such controls do not appear in VB Editor Must assign a macro to the control

Page 26: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 26 © All Rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 2: Drill-Down Chart

The goal of this exercise is to

Create a drill-down chart presentation

Page 27: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 27 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 2: Drill-Down Chart

Objective In this exercise, you will learn how to • Use Chart events and Forms controls to create a drill-down

chart presentation Overview You have been given a workbook, which contains sales data for a food store. The data is divided into food groups and further subdivided into single food items. A totals chart (Chart1) and a subchart for one of the groups (Chart2) have already been created by an ordinary Excel developer. Your job is to create drill-down functionality. To simplify maintenance and reduce memory requirements, you believe that you can get by with just one subchart, customizing it to one group at a time. (Actually you could manage with just one chart altogether, but we will stop short of that.)

Page 28: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 28 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 2: Drill-Down Chart

(continued)

1. Open C:\cse209\Input\FoodSales.xls. Look at the different worksheets and chart sheets to acquaint yourself with their content.

Writing code so that a double-click on one of the bars in the TotalsChart opens a corresponding SubChart

2. Open VB Editor and identify the TotalsChart module. Enter the following code in its BeforeDoubleClick event: Dim serData As Series Set serData = Chart2.SeriesCollection(1) If ElementID = xlSeries Then Cancel = True serData.Values = _ Worksheets(Arg2 + 1).Range("B2:G2") serData.XValues = _ Worksheets(Arg2 + 1).Range("B1:G1") Chart2.ChartTitle.Text = _ Worksheets(Arg2 + 1).Range("H1").Value Chart2.Activate End If

Use the online Help to answer the following: a. What does Arg1 signify for a series? b. What does Arg2 signify?

Page 29: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 29 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 2: Drill-Down Chart

(continued)

3. Click any of the bars (not a double-click) to select first the

series and then the individual bar. Now test the code by double-clicking any of the bars.

Warning! Double-clicking a bar without first selecting one of the bars will result in a runtime error.

Adding a button to return to the TotalsChart from SubChart

4. Create a procedure in a standard module as follows: Public Sub BackToTotals() Chart1.Activate End Sub

5. Open the SubChart sheet in the Excel environment.

6. Open the Forms toolbar and add a button to the chart.

The Assign Macro dialog should open automatically.

If it does not, right-click the control and select Assign Macro.

7. Assign the BackToTotals macro to the button.

Page 30: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 30 © All rights reserved. Not to be reproduced by any means without prior written consent.

Hands-On Exercise 2: Drill-Down Chart

(continued)

8. Test to see that the new functionality works as expected.

You may have noticed that the tooltip for the new button says “Button 1,” which is not very enlightening. One way of changing the tooltip text is to open the Immediate window in VB Editor and type the following: Chart2.Shapes(1).Name="Return to Totals" The button is the (only) Shape object on this chart, and changing its name will change the tooltip.

Congratulations! You have added functionality to Excel charts to create drill-down features.

Find a way to minimize the problem with the initial selection of one data point.

This is the end of Hands-On Exercise A.2.

Page 31: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 31 © All rights reserved. Not to be reproduced by any means without prior written consent.

More Excel VBA

Pivot Tables

Charts

Summary

Page 32: Course 209 Supplementary Materials More Excel VBA

More Excel VBA Course 209

www.LearningTree.com 32 © All rights reserved. Not to be reproduced by any means without prior written consent.

Summary

We have looked at VBA and pivot tables VBA in Excel charts