automating excel with macros

110
Automating Excel With Macros Course 4612 4612/CN/A.2/504/A.1

Upload: others

Post on 02-May-2022

27 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Automating Excel With Macros

Automating Excel With Macros

Course 4612

4612/CN/A.2/504/A.1

Page 2: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

© LEARNING TREE INTERNATIONAL, INC.All rights reserved.

All trademarked product and company names are the property of their respective trademark holders.

No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, or translated into any language, without the prior written

permission of the publisher.

Copying software used in this course is prohibited without the express permission of Learning Tree International, Inc. Making unauthorized copies of

such software violates federal copyright law, which includes both civil and criminal penalties.

Page 3: Automating Excel With Macros
Page 4: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Guide to Learning Tree International Excel Courses

Course 1361: Excel Introduction (3 days)

Course 4610: Excel Workbooks (1 day)

Course 195: Power Excel, Analyzing Data (2 days)

Course 4611: Excel PivotTables (1 day)

Course 1362: Power Pivot for Excel (2 days)

Course 4612: Excel Macros (1 day)

Start

Course 209: VBA Programming Introduction (4 days)

Page 5: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Common Excel Activities

Data

SageExcel

Text FilesExcel

SQL ServerOracle

HR

Sales and Marketing

Accounting

IT

Administration

SAPPeopleSoft

ExcelAccess

Validate/modify data

Analyze data

Create reports

Create dashboard

Create invoices

E-mail and print

Publish to SharePoint

Print

Workbook activities

Page 6: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Course Objectives

In this course, you will develop the skills to

Create macros to automate saving data into multiple worksheets

Execute macros via macro buttons, toolbar buttons, and keystrokes

Examine code statements to understand VBA principles

Interpret and troubleshoot code in the Visual Basic Editor

Modify and enhance a macro

Incorporate code snippets taken from the web into your own solutions

Identify and extract values from cells in VBA

Customize a macro and manage information using variables

Design user-friendly interfaces with form controls

VBA = Visual Basic for Applications

Page 7: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Course Contents

Introduction and Overview

Chapter 1 Identifying Workbook Processes for Automation

Chapter 2 Automating Processes With Macros

Chapter 3 Extending Macro Functionality With Variables and Controls

Chapter 4 Course Summary

Next Steps

After-Course Activities

Practice Practice Practice

Page 8: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

The Course Layout

Hands-on exercises• To help master concepts• Based on real-world scenarios• Some are instructor-led

Do Now exercises• Short exercises• Typically instructor-led

Demos• Solely performed by the instructor• Excel features to be aware of

Page 9: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

The Exercise Setup File

Shortcut to exercise file

Page 10: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Access to Command Notation in Exercises

Example: If you see Home | Alignment | Wrap Text• Means go to the Alignment group in the Home tab and select the Wrap Text

command

1

2

3

Page 11: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

A Snapshot of Microsoft Excel’s History

This course • Runs on Microsoft Excel 2013

100 percent of the course material applies to all versions

OLAP = online analytical processing XML = extensible markup language

Excel 97: Major upgrade from Excel 95

Excel 2000: Minor upgradePivotChart reports, OLAP source data

Excel XP (2002): Minor upgradeXML support, Smart Tags, improved Audit tools

Excel 2003: Minor upgradeXML files, List features, upgraded calculations

Excel 2007: Major upgradeRibbon introduced; interfacerevamped; faster calculations; charts

Excel 2010: Minor upgradeSlicer; sparklines; charts; Power Pivot; Power Query

Excel 2013: Major upgradexVelocity engine; Relationships; Power View; Power Map

Page 12: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Prerequisite Knowledge

Let your instructor know if you do not know how to do any of the following:

Selecting, moving, and copying cells • Using Cut/Copy and Paste or AutoFill

Recognizing mouse shapes and their function

Resizing columns

Inserting an Excel sheet

Filtering in PivotTables

Implementing calculations in Excel using functions • Such as SUM/IF/VLOOKUP

Page 13: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Excel Features Used in the Course Examples

AutoFilter• Automate creating a summary table using different filters

PivotTables• Automate changing the report filter for multiple PivotTables

Functions• The INDEX function is used in an example• Course 195 can help you with interpreting functions

Chart• Automate updating a chart with different sets of values

Let your instructor know if you are concerned about any of the above

Page 14: Automating Excel With Macros

© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Are You in the Right Course?

Do the course objectives meet your needs?• No

– Tell your instructor now– He or she can help you find the right course

• Yes– Ensure that the instructor has your questionnaire

Page 15: Automating Excel With Macros
Page 16: Automating Excel With Macros

Identifying Workbook Processes for Automation

Chapter 1

Page 17: Automating Excel With Macros

21-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Objectives

In this chapter, you will learn how to• Describe the purpose of an Excel macro• Recognize processes to automate• Identify automation problems within inherited workbooks

You will also become aware of Excel features that can enhance productivity

Page 18: Automating Excel With Macros

31-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

DemoWhat Is an Excel Macro?

Set of instructions written in Visual Basic for Applications (VBA)

Created by• Recording a sequence of actions• Manually writing code from scratch

From 2007: must be saved in macro-enabled workbook (.xlsm)

Used to• Combine a series of actions into a single step• Automate repetitive actions• Improve functionality of a workbook model• Reduce possibility of human error• Store complex sequences instead of

relying on an individual

Page 19: Automating Excel With Macros

41-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Identifying When a Macro Is Required

Repetitive: Is there a task you are doing daily, weekly, or monthly?• Importing a dataset daily into a workbook

– Ensuring that calculations are correct– Ensuring that related charts and PivotTables are updated

Usability: Do others have to use the workbook model that you created?• User should be able to see

– Cells and/or areas where input is required– Key performance indicators

Complex: Is there a task that requires a number of steps?• Example: importing data, splitting it into different

categories, removing irrelevant rows of data, formatting numbers, then creating invoices, paymentschedules and remittances

Page 20: Automating Excel With Macros

51-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Identify Excel Tasks That You Do

1. Repetitive: Is there a task you are doing daily, weekly, or monthly?

2. Usability: Do others have to use the workbook model that you created?

3. Complex: Is there a task that requires a number of steps that you perform infrequently?

I wonder if a macro would be best suited to complete this task?

Page 21: Automating Excel With Macros

61-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Need to change the filter of several PivotTables to the same item• Versions previous to 2010 need a macro

Every week, I import a date-stamped CSV file into Excel and then have to tidy up the table• If filename is always the same

– Set up data connections and functions• If filename varies

– Record a macro that applies to one file, then modify macro

Need to log changes made to a form• Record a macro, then modify to improve its capabilities

Need to extract a sequence of entries from a dataset to create a summary• Function knowledge must be good• Many revert to using macros

Can cause problems if dataset grows

Excel Processes to Automate

CSV = comma-separated value

Page 22: Automating Excel With Macros

71-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Features That Automate Common Workbook Tasks

Excel contains features that automate many common tasks• Functions• Conditional formatting• PivotTables• Styles• Tables• Microsoft Query/data connections

Use these features when practical instead of macros!

4610

1361

4611

195

1362

Page 23: Automating Excel With Macros

81-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Macros or Functions?

1. From the Exercise Setup workbook | Do Now and Demos, open the workbook called TruckDemoMacro

2. Examine the Truck Plan Macro worksheet. Click the “Create Summary For All” button to play a macro providing a summary in a tablea. What are the macro’s limitations?

b. What if the dataset expands?

3. Examine the other worksheet to see a function providing a summarya. What are the limitations of the function?

b. What if the dataset expands?

4. How can the design of the worksheet that uses a macro be improved?

Page 24: Automating Excel With Macros

91-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Macro Dangers

Maintainability and usability issues• Poor design principles

– Calculations are slow/incorrect

Broken macros• Logic-related

– Worksheet names changed– Cell references changed

• Incorrect dataset references• Changed cell references to

values

Page 25: Automating Excel With Macros

101-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

The Visual Basic Editor (VBE)

For some users, VBE = Very Bad Environment!

Page 26: Automating Excel With Macros

111-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Summary

In this chapter, you have learned how to• Describe the purpose of an Excel macro• Recognize processes to automate• Identify automation problems within inherited workbooks

You have also became aware of Excel features that can enhance productivity

Page 27: Automating Excel With Macros

121-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1. What is a macro?A. Special tool that automates large tasksB. Special tool that automates a datasetC. A recording of a sequence of actions that can be played back as if they were

one actionD. Written in a language called Visual Basic for Application

2. What extension can a workbook with a macro have?A. .xlsxB. .xlsmC. .xltxD. .xls

3. What should you consider before creating a macro?A. Check the web/forums for Excel tools/functions that might automate tasksB. Anyone can support a macroC. A macro should always be the first choiceD. A macro should be the last choice

Chapter Review

Page 28: Automating Excel With Macros

Automating Processes With Macros

Chapter 2

Page 29: Automating Excel With Macros

22-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Objectives

In this chapter, you will learn how to

Create macros to repeat a series of user actions

Make macros easily accessible to the end user

Identify the basic principles of a macro procedure

Decipher macro code in the Visual Basic Editor

Recycle code from the web into your own solution

Enhance code to save newly created data with the Offset VBA property

Page 30: Automating Excel With Macros

32-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Creating Macros Hands-On Exercise 2.1

Exploring How a Macro Works

Instructor-Led Exercise 2.2

Recycling Code/Offset Property

Hands-On Exercise 2.3

Page 31: Automating Excel With Macros

42-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

How to Record a Macro

Creating a macro is like using a recording device1. Plan steps of macro

– All actions in Excel are recorded (see next slide)

2. Prepare to record new macro– Select View | Macros | Macros

| Record Macro– Fill in the options

3. Click OK to begin recording process4. Perform actions identified in Step 15. Stop recording6. Play back recording

Stop Recordingappears on Status Bar

In 2003: • Select the menu options Tools | Macro | Record New Macro• Stop recording by clicking the stop button on the Stop Recording Toolbar

Page 32: Automating Excel With Macros

52-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

What Is Recorded

Excel records all actions within the application, such as• Typing text• Any special keys you use; e.g.:

– Arrow keys– Function keys– Key combinations; e.g. <Ctrl><C>

• Clicking and scrolling with mouse• Selecting a range or an object• Selecting characters in a cell

What is not recorded:• Any keystrokes or mouse actions

outside of Excel

209

Validate/modify data

Analyze data

Create reports

Create dashboard

Create invoices

E-mail and print

Publish to SharePoint

Print

Workbook activities

Page 33: Automating Excel With Macros

62-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Macro name• Must start with a letter• Can contain letters, digits, and underscores

– No spaces • Up to 255 characters

– Use initial capitalization for readability• Cannot be a reserved word

– Blue words in VBA

Which of these names is valid?

• Create Monthly Report ___________________

• 2ndQuarterlyTotal ___________________

• UpdatePivotTableFilter ___________________

Filling in the Record Macro Dialog Box

Page 34: Automating Excel With Macros

72-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Filling in the Record Macro Dialog Box

Shortcut key• Assign a shortcut key to run macro

Store macro in• This Workbook/New Workbook

– Macros available when workbook is open• Personal Macro Workbook

– Macros available when Excel launched

Description• Fill in to indicate what macro does

Page 35: Automating Excel With Macros

82-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Running the Recorded Macro

Select View | Macros | Macros | View Macros• Select the macro to execute, then click the Run button

Alternatively, run the macro from a• Shortcut key• Button from Forms toolbar• Quick Access Toolbar button• Ribbon command (2010/2013)

In 2003: • Select the menu options Tools | Macro | Macros

Page 36: Automating Excel With Macros

92-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1. In a new workbook, start the macro recorder

To create a new workbook, press <Ctrl><N>

Macro recorder: View | Macros | Macros | Record Macro

2. In the Record Macro dialog box:a. Macro name = MyName; Shortcut key = <Ctrl><Shift><M>

3. Record entering your name in the active cell

4. Stop recording macro: Click Stop button in Status Bar

5. Play back macro using shortcut key:a. Select any cell on any worksheet and test macrob. In a new workbook, test that macro worksc. Save workbook containing macro and close. Test if macro still works!Create a macro that enters your name in any cell and is always available

Store the macro in the Personal Macro Workbook. You will be prompted to save this workbook when you close Excel

Macro to Enter Your Name in Any Cell Do Now

Page 37: Automating Excel With Macros

102-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Displaying the Developer Tab (Excel 2007 and later)

Contains tools specifically for developing workbooks

In 2010 and later:1. File | Options2. From Customize Ribbon

tab, select Developer

In 2007: 1. Office button | Excel Options2. From Popular tab, select “Show Developer tab in the Ribbon”

Page 38: Automating Excel With Macros

112-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Assigning a Macro to a Button From Form Controls

1

2

3

4

In 2003: • Create a Form button by using the Forms toolbar

Developer | Controls | Insert

Page 39: Automating Excel With Macros

122-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Assigning a Macro to a Form Button

1. From Ribbon, select Developer | Controls | Insert

2. From Form Controls, click the Button control and draw on worksheet

3. Release mouse button to display Assign Macro dialog box

4. Select macro to run, and click OK

5. Enter a descriptive caption on button• Just start typing!

6. Deselect button by clicking a worksheet cell

7. Click button to run macro• Mouse shape is a hand

In 2003: • In place of Step 1 above, display the Forms toolbar: View | Toolbars | Forms

Page 40: Automating Excel With Macros

132-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Modifying a Form Button

Right-click button• Selects it and displays a shortcut menu• Change button caption• Assign a different macro to the button

Press <Ctrl> while clicking to select form button without shortcut menu

Page 41: Automating Excel With Macros

142-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Creating Macros

Hands-On Exercise 2.1 Exploring How a Macro Works

Instructor-Led Exercise 2.2

Recycling Code/Offset Property

Hands-On Exercise 2.3

Page 42: Automating Excel With Macros

152-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

This course is AdaptaLearn Enabled• Web technology has allowed us to produce “dynamic documents”

Steps and hints can be “folded” in and out to give increasing levels of detail, providing you with a tailored experience• Suitable to your personal background and work style• Answers to questions also can be folded and unfolded

AdaptaLearn also provides:• Simplified “copy and paste” of solution code

– Decreases need to search through files on the course load

• Internet links to other helpful information• Video playback for especially difficult actions• Ability to use outside of class for continued reference and practice

AdaptaLearn is easy to use• For your convenience, a paper copy of the Exercise Manual is also provided

– All detail levels are shown (hints and answers are unfolded)

AdaptaLearn™ Enabled

Page 43: Automating Excel With Macros

162-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Do Now

Let’s try it now1. Launch AdaptaLearn by double-clicking its icon on the desktop2. Move the AdaptaLearn window to the side of your screen, or minimize it

so it is a thin strip across the top or bottom– Leave room for a work area for your development tools

3. Select the first exercise from the exercise menu4. Use <Ctrl><mouse_wheel> to change the font size as desired5. If your screen is small or you want to maximize the AdaptaLearn window,

use <Alt><Tab> to toggle back and forth6. A folded area is introduced in blue text

– Click the text to see how folds work7. A copy-and-paste area is in a blue box

– Hover over the box (but don’t click on it) and press <Ctrl><C>

Using AdaptaLearn™

Page 44: Automating Excel With Macros

172-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

The Exercises

Access through the Exercise Setup program when described

Written as follows:• Objectives• Business case to solve• Major Step

1. Main action2. Main action described

a. Sub-step to break down the action you are learning to perform

Checkpoint Hint WarningQuestion Information

Congratulations—what features you have learned to use

Bonus—extra exercises (not all students will have time to complete)

• Stop—end of the main exercise or bonusSTOP

Page 45: Automating Excel With Macros

182-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Hands-On Exercise 2.1

In your Exercise Manual, please turn toHands-On Exercise 2.1: Easing Repetitive Tasks

Main exercise Dan would like to use an AutoFilter process to analyze his truck configuration. However, he is taking a long time to do the task. You will help him create a macro to provide a summary for truck A.

Bonus • Record a macro that will create a summary table for all the different trucks

• Assign a macro to a toolbar icon

Page 46: Automating Excel With Macros

192-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1. What extension can a workbook with a macro have?A. .xlsxB. .xlsmC. .xltxD. .xls

2. How can a macro be invoked?A. Assign a macro to a drawing shapeB. Assign a macro to a form controlC. Assign a macro to the Quick Access ToolbarD. Assign a macro to the Ribbon

3. Where are the form controls?A. In the Drawing shapes in the Insert tabB. In the Developer’s tab—activated in File | Options | Customize RibbonC. In the View tab, Macros commandD. In the Home tab, Form controls

Review Quiz

Page 47: Automating Excel With Macros

202-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Creating Macros

Hands-On Exercise 2.1

Exploring How a Macro Works Instructor-Led Exercise 2.2

Recycling Code/Offset Property

Hands-On Exercise 2.3

Page 48: Automating Excel With Macros

212-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

What are the problems with recording long macros?• Especially with repetitive steps?

Problem With Recording Summary For All Trucks

Page 49: Automating Excel With Macros

222-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Taking Your First Steps in VBA

Recorded macros• Good starting point to learn VBA• Limited to only user actions

Modify existing VBA to extend a macro’s capabilities• Interacting with user• Automating with other applications• Performing similar actions multiple times

Result of recording a macro = VBA

Page 50: Automating Excel With Macros

232-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Exploring the Visual Basic Editor (VBE)

Development environment hosted within Excel

Appears as a separate program when launched

Page 51: Automating Excel With Macros

242-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Reference

Project• A collection of modules• Is the workbook!

Modules• Contains procedures, including macros

Macro or procedure• Macro: is a type of procedure

– Often recorded• Procedure: describes a general programming component

– Used to enhance macros

Statement• Normally a single line of code• Space underscore ( _ ) continues a single logical line onto a second physical

line• Syntactically complete unit expressing an action, declaration, or definition

Jargon Buster: Working With Code

Page 52: Automating Excel With Macros

252-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Debugging: Locating the Macro in the VBE

Page 53: Automating Excel With Macros

262-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Remember: The end result of recording a macro is VBA code

How do you display the Macro dialog box?

How do you locate the macro associated with a button?

Clicking Step Into will display VBE and go into break mode• Yellow highlighting indicates line to be executed

Clicking Edit will display VBE• Shows the VBA code behind macro

Debugging: Locating the Macro VBA in the VBE

Press <F8> to execute highlighted line of code and move to next line of codePress <F5> to continue a macro’s execution until the end

Page 54: Automating Excel With Macros

272-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Debugging: Examining How a Macro Works

To troubleshoot, display both User Interface (UI) and VBE

Page 55: Automating Excel With Macros

282-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Creating Macros

Hands-On Exercise 2.1

Exploring How a Macro Works

Instructor-Led Exercise 2.2 Recycling Code/Offset Property

Hands-On Exercise 2.3

Page 56: Automating Excel With Macros

292-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Instructor-Led Hands-On Exercise 2.2

In your Exercise Manual, please turn toInstructor-Led Hands-On Exercise 2.2: Examining Macros

Main exercise Instead of having one macro per truck summary, we will look at summarizing all the truck configurations with one macro.

Bonus The truck workbook was created in Excel 2003 and is now being used in a later version of Excel. When the macro is run, an error occurs. You will fix this.

Page 57: Automating Excel With Macros

302-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

What two lines show the beginning and the end of a macro?

Name some reserved words. How do you know they are reserved?

Which lines of code are not executed? (These are called comments)

How do you refer to a specific cell(s) in a worksheet?

Understanding the Workings of a Macro

Page 58: Automating Excel With Macros

312-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Creating Macros

Hands-On Exercise 2.1

Exploring How a Macro Works

Instructor-Led Exercise 2.2

Recycling Code/Offset Property Hands-On Exercise 2.3

Page 59: Automating Excel With Macros

322-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

QuizWorking With Code Snippets

You find the following code snippet on the web to automate importing a text file into an Excel worksheet in the current workbook.

Where do you put this code to run it?

What two lines do you need to add to the code to test it and to see whether it works?

Const csPath As String = "C:\Test\Example.csv"Dim ws As Excel.WorksheetSet ws = Excel.ActiveSheetWith ws.QueryTables.Add("TEXT;" & csPath, ws.Cells(1, 1)).FieldNames = True.AdjustColumnWidth = True.TextFileParseType = xlDelimited.TextFileTextQualifier = xlTextQualifierDoubleQuote.TextFileConsecutiveDelimiter = False.TextFileCommaDelimiter = True‘***This array will need as many entries as there will be columns:.TextFileColumnDataTypes = Array(xlTextFormat, xlTextFormat).RefreshEnd With

Page 60: Automating Excel With Macros

332-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Recycling Macros

Separate units of functionality into separate procedures• Aids manageability and reusability

Example:

• Open file from a folder into ExcelImport CSV File

• Remove spurious characters from text and convert to tableTidy Up

• Refresh associated PivotTablesRefresh PivotTables

• Print required reportPrint Report

Page 61: Automating Excel With Macros

342-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

DemoCalling Procedures

Each procedure performs an action• Can execute procedure

individually via interface• Can execute procedure

in another procedure

Use• Procedure name

– ImportCSV

• Call <ProcedureName>– Call ImportCSV()

Page 62: Automating Excel With Macros

352-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Expression.Offset(RowOffset, ColumnOffset)

• RowOffset = Number of rows to offset by• ColumnOffset = Number of columns to offset by

What cell is being referred to in the following?

• Range("A1").Offset(2,4)

• Range("A1").Offset(0,4)

• Range("D6").Offset(-3,0)

The Offset VBA Property

Offset allows you to omit the row or column offset when it is zero. The last two code snippets can be rewritten as Range("A1").Offset(,4) and Range("D6").Offset(-3)

Note: A comma is required when the RowOffset is omitted.

Page 63: Automating Excel With Macros

362-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Creating Macros

Hands-On Exercise 2.1

Exploring How a Macro Works

Instructor-Led Exercise 3.2

Recycling Code/Offset Property

Hands-On Exercise 2.3

Page 64: Automating Excel With Macros

372-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Hands-On Exercise 2.3

In your Exercise Manual, please turn toHands-On Exercise 2.3: Tracking New Records

Main exercise The project managers would like you to help them log projects and their respective resources into different tables when the projects are saved.

Bonus You will include code that was taken from the web and use it in your own solution to save data into CSV format.

Page 65: Automating Excel With Macros

382-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Summary

In this chapter, you have learned how to

Create macros to repeat a series of user actions

Make macros easily accessible to the end user

Identify the basic principles of a macro procedure

Decipher macro code in the Visual Basic Editor

Recycle code from the web into your own solution

Enhance code to save newly created data with the Offset VBA property

Page 66: Automating Excel With Macros

392-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

QuizChapter Review

1. When the macro recorder is switched on, what tasks are recorded?

2. Where do you edit the code for a macro?

3. What function key can be used to a. Single-step through code?b. Execute code to the end?

4. You find code on the web. If you want to run it in your own solution, what do you need to do?

Page 67: Automating Excel With Macros
Page 68: Automating Excel With Macros

Extending Macro Functionality With Variables and Controls

Chapter 3

Page 69: Automating Excel With Macros

23-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Objectives

In this chapter, you will learn how to

Create variables in VBA

Identify common variable errors

Incorporate variables into existing macros

Capture user inputs with form controls

Connect controls to the worksheet

Create user interactive forms

Page 70: Automating Excel With Macros

33-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Manipulating Information With Variables

Hands-On Exercise 3.1

Creating Interactive Interfaces

Hands-On Exercise 3.2

Page 71: Automating Excel With Macros

43-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Reference

Named location in memory• Temporary storage area for information• Contents changed in code

Used to make macros more dynamic• In statements and expressions

Naming rules of variables are identical to macro naming rules

Similar to named ranges• Can contain variable information

– Changed by changing contents of named cell(s)

• Can be used in formulas

Jargon Buster: Variables

Variable

Variable

Variable

Variable

Variable

Page 72: Automating Excel With Macros

53-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

How to Create a Variable

Create by dimensioning or declaring the variable• Dim <VariableName> As <DataType>

Declaring variables as a specific data type provides• Type of information/range of values to use• Required amount of space in memory

Page 73: Automating Excel With Macros

63-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

ReferenceData Types: Simplified Overview

Name Prefix* Description Range RAM Initial value

Byte byt Numeric, Integer 0 to 255 1 0

Boolean bln Binary True or False 2 0

Integer int Numeric, Integer –32,768 to 32,767 2 0

Long lng Numeric, Integer –2,147,483,648 to 2,147,483,647 4 0

LongLong** llg Numeric, Integer -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 8 0

Single sng Numeric, any +/– 1.4 * 10–45 to +/– 3.4 * 1038 4 0

Double dbl Numeric, any +/– 4.9 * 10-324 to +/– 1.8 * 10308 8 0

Currency cur Numeric, any –922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 0

Date dtm Date and Time Jan 1, 100 to December 31, 9999 8 0

Object obj Any Object Any object reference

String str Text 0 to 2 billion (fixed length: 64K) 1/char “”

Variant vnt Any of the above Any Min 16 Empty

*Follows the Leszynski naming convention**Only available to 64-bit Office 2010/2013

Page 74: Automating Excel With Macros

73-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Examples of Working With Variables

Assigning values to variables/writing to variables:

Dim intPalletTotal As IntegerintPalletTotal = Range(“F432”).Value

Dim strPivotFilter As StringstrPivotFilter = Range(“A2”).Value

Extracting/reading contents of variables:

Range(“B2”).Value = intPalletTotalMsgBox strPivotFilter

Page 75: Automating Excel With Macros

83-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

1. In a new workbook, create a new macro called VariableTest

To create a new workbook press <Ctrl><N>

Select View | Macros | Macros. In the dialog box, enter the macro name and click Create

2. In the macro, create the following code:a. Create a byte variable called MyHappyVariableb. Assign the variable the contents of cell A1c. Put the contents of the variable into cell C1

3. Run the code with the tabulated information and enter what happens

Instructor-Led: Data Types and Variables

Value in cell A1 What happened when you ran the macro?

255

256

aaa

Do Now

Page 76: Automating Excel With Macros

93-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

4. Remove the data type from the code, then rerun the code with the different tabulated information and record what happens

If no data type is specified, the variable is assigned a default data type. What do you think is the default data type?

Instructor-Led: Data Types and Variables

Value in cell A1 What happened when you ran the macro?

255

256

aaa

Do Now

Page 77: Automating Excel With Macros

103-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Default data type = Variant• Holds any type of value or object• Slow compared to other variable

What is the declaration statement to create a variant variable?

______________________________________________________________

You can declare several variables on the same line• Must give each variable a data type• Dim intPalletTotal, intTruckWeight As Integer

– Makes intPalletTotal a variant

Specify smallest data type, but leave room for growth• Improves performance of large program using many variables

Exploring the Variant Data Type

Page 78: Automating Excel With Macros

113-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

QuizWhich Data Type?

Based on existing data, how would you declare a variable for column B?

Based on existing data, how would you declare a variable for column C?

Page 79: Automating Excel With Macros

123-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

QuizMaking a Macro Dynamic

You have to automate changing the Report Filter for two PivotTables to the same value as in cell A2

How do you find out what code is required to change the country used in each PivotTable filter?

Page 80: Automating Excel With Macros

133-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

QuizMaking a Macro Dynamic

What code modifications need to be made to extract the value from cell A2 in order to use the value in the filter for each PivotTable?

Page 81: Automating Excel With Macros

143-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Manipulating Information With Variables

Hands-On Exercise 3.1 Creating Interactive Interfaces

Hands-On Exercise 3.2

Page 82: Automating Excel With Macros

153-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Hands-On Exercise 3.1

In your Exercise Manual, please refer to Hands-On Exercise 3.1: Manipulating Code With Variables

Main exercise You will record a macro that changes the page filter for multiple PivotTables, then edit the macro to incorporate variables.

Bonus You will use variables to modify versions of the macros you created previously.

Page 83: Automating Excel With Macros

163-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Variables can be implicitly created• Causes errors in the process if inconsistent

What do you think will appear in the report filter for each PivotTable?

Potential Problems With Variables In Code

' 3a. Create a string variableDim strPivotFilter As String' 3b. Assign the contents of A3 to the variablestrPivotFilters = Range("A3")' 3c. Change the code to use the string variableActiveSheet.PivotTables("PivotTable1").PivotFields("COUNTRY").CurrentPage = _

strPivotFiltersActiveSheet.PivotTables("PivotTable2").PivotFields("COUNTRY").CurrentPage = _

strPivotFilter

Page 84: Automating Excel With Macros

173-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

In existing modules, add Option Explicit at the top of module

Before a module is created, switch on Require Variable Declaration• Tools | Options | Require Variable Declaration

Preventing Undeclared Variables

Page 85: Automating Excel With Macros

183-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Preventing Undeclared Variables

Page 86: Automating Excel With Macros

193-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Manipulating Information With Variables

Hands-On Exercise 3.1

Creating Interactive Interfaces

Hands-On Exercise 3.2

Page 87: Automating Excel With Macros

203-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Extending Macro Solutions With User Interfaces

Control user interaction with the workbook• Display limited choices to user• Example: Control a dashboard on a worksheet

Consolidate user inputs• Directs user to inputs that need to be modified• Can use worksheets, dialog sheets, and UserForms (VBE)

Form Controls on a dialog sheetForm Controls on a worksheet

Page 88: Automating Excel With Macros

213-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Adding Controls for User InputAdvantages Disadvantages

Form Controls on Worksheets

• Easy to use • Place controls directly on the

worksheet (input worksheet)• Controls can have a macro

assigned to them

• Can make worksheet cluttered

• User has to switch back to input worksheet to make changes

Form Controls on Dialog Sheets

• Easy to use• Place controls directly on

dialog sheet• Controls can have a macro

assigned to them• Can be displayed in any

worksheet• Can be easily hidden

• Knowledgeable user can unhide dialog sheet and make unwanted changes

ActiveX Controls on UserForms (VBE)

• Can be displayed in any worksheet

• User must know how to use VBE to make changes

• Must be created in the VBE• Requires more knowledge• Requires more code

209

Page 89: Automating Excel With Macros

223-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Form Controls vs. ActiveX Controls

Form controls• Simpler set of properties• Used only on worksheets and dialog sheets

ActiveX controls• Complex set of properties• Used only on UserForms (VBE) and worksheets

– Not in dialog sheets• Course 209, VBA Programming Introduction

®

209

Page 90: Automating Excel With Macros

233-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Working With Form Controls

Add a control• Click control in toolbox and draw it on dialog sheet/worksheet

Move a control by selecting and dragging it• May have to right-click to select it first

Size a control by dragging one of its sizing handles• Cursor changes to a double-sided arrow

Page 91: Automating Excel With Macros

243-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Option Buttons and Checkboxes

Option buttons• Only a single selection is allowed• Use group box to create multiple option button areas• Values start from 0 and correspond to option button

selected

Checkboxes allow the user to specify conditions• Any number of boxes can be selected simultaneously• Values can be TRUE, FALSE, #N/A

Page 92: Automating Excel With Macros

253-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

List Controls List box

• Select one or more items• Populate using Input Range field• Link to a cell using Cell Link field

Combo box• Select one item only• Has similar properties to list box• Displayed as a drop-down list box

Page 93: Automating Excel With Macros

263-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Modifying Control Properties

1. Right-click control and select Format Control

2. Modify appropriate fields

Page 94: Automating Excel With Macros

273-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Control Properties

Cell Link property is a cell that is linked to the control• Changing control state changes linked cell value

Changing the linked cell value changes the control state• Cells linked to checkboxes can be set to TRUE, FALSE, or #N/A• Cells linked to option buttons have a corresponding number value

– Starting with zero• Cells linked to list boxes have a number corresponding to selected value

Page 95: Automating Excel With Macros

283-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Adding a Dialog Sheet

1. Right-click an existing sheet tab to display shortcut menu

2. Select Insert from the shortcut menu to display the Insert dialog box

3. Select the MS Excel 5.0 Dialog icon and click OK

Page 96: Automating Excel With Macros

293-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Working With the Dialog Sheet

Dialog sheet supports Form Controls• Used to add controls to the dialog sheet

Test dialog sheet by selecting Run Dialog icon• Can record pressing Run Dialog in a macro

Page 97: Automating Excel With Macros

303-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Contents

Manipulating Information With Variables

Hands-On Exercise 3.1

Creating Interactive Interfaces

Hands-On Exercise 3.2

Page 98: Automating Excel With Macros

313-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Hands-On Exercise 3.2

In your Exercise Manual, please refer to Hands-On Exercise 3.2: Creating Interactive User Interfaces

Main exercise You will examine how controls can be used to simplify the way a worksheet works.

Bonus You will design a dialog sheet to capture user specifications.

Page 99: Automating Excel With Macros

323-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Next Step

Course 209• VBA Programming Introduction• Introduces Visual Basic for Applications (VBA) programming

– No programming knowledge required

Course 971• Building Applications with Microsoft Access®: Hands-On• Automates Access database solutions with macros and VBA

– Access knowledge to the level of 970 is assumed

209

Page 100: Automating Excel With Macros

333-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Chapter Summary

In this chapter, you have learned how to

Create variables in VBA

Identify common variable errors

Incorporate variables into existing macros

Capture user inputs with form controls

Connect controls to the worksheet

Create user interactive forms

Page 101: Automating Excel With Macros

343-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

QuizChapter Review What is the default data type for a variable?

What are two typical errors you will see when variables are used in code?

How do you know what data type to use?

Where do you find controls to add to a worksheet or dialog sheet?

How do you use controls on a:• Worksheet?• Dialog sheet?

Page 102: Automating Excel With Macros

Course Summary

Chapter 4

Page 103: Automating Excel With Macros

24-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Course Summary

In this course, you have developed the skills to

Create macros to automate saving data into multiple worksheets

Execute macros via macro buttons, toolbar buttons, and keystrokes

Examine code statements to understand VBA principles

Interpret and troubleshoot code in the Visual Basic Editor

Modify and enhance a macro

Incorporate code snippets taken from the web into your own solutions

Identify and extract values from cells in VBA

Customize a macro and manage information using variables

Design user-friendly interfaces with form controls

Page 104: Automating Excel With Macros

34-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Guide to Learning Tree International Excel Courses

Course 1361: Excel Introduction (3 days)

Course 4610: Excel Workbooks (1 day)

Course 195: Power Excel, Analyzing Data (2 days)

Course 4611: Excel PivotTables (1 day)

Course 1362: Power Pivot for Excel (2 days)

Course 4612: Excel Macros (1 day)

Start

Course 209: VBA Programming Introduction (4 days)

Page 105: Automating Excel With Macros

44-© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent.

Related Learning Tree Courses

1-DAY BOOT CAMP Courses:• Creating and Designing Excel Workbooks—Course 4610• Excel PivotTables: Building Dashboards—Course 4611

Multi-Day Courses:• Microsoft Excel Introduction—Course 1361• Power Excel: Analyzing Data to Make Business Decisions—Course 195• Power Pivot for Excel: Mining Data for Business Intelligence—Course 1362

For more information on these and other related courses, please visit: LearningTree.com/MicrosoftOffice

Page 106: Automating Excel With Macros

Bonus Session

Appendix A

Page 107: Automating Excel With Macros

2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. AppA-

Create a macro that refers to a cell within a workbook to open up a specific workbook

Implement a drop-down list box that displays a list of workbooks that can be opened, and use the code from the previous macro to open the workbook that is selected from the drop-down

You can use the INDEX() function to identify the selection. See the screenshot below for an example

Bonus Exercise A.1

Page 108: Automating Excel With Macros

After-Course Activity—Sandbox

Appendix B

Page 109: Automating Excel With Macros

2© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. AppB-

You will create several macros that will create a report from a CSV file and then save the file with the same name, but as an .xlsx into a “save” folder. Many of the macros will need to be modified to make them more dynamic.

1. Create a macro that refers to a couple of cells that indicates a folder and a CSV file that is to be imported into the workbook (see screenshot below)

2. Create a second macro that applies a table format to the data as specified by a cell value in the worksheet (see screenshot below)

3. Create a third macro that creates a PivotTable report of the data showing how much revenue each product has brought into the company. Display the PivotTable report as a pie chart

After-Course Sandbox: Streamlining a Process

Page 110: Automating Excel With Macros

3© Learning Tree International, Inc. All rights reserved. Not to be reproduced without prior written consent. AppB-

4. Create a fourth macro that deletes the worksheet that contains the input

5. Create a final macro that saves a workbook as a .xlsx fileYou do not want to save the current workbook as a .xlsx; otherwise, it will remove your macro code!

6. Find code on the web to extract the filename of the CSV, then use the filename as the workbook name

7. Combine the macros so that they run from one procedure

8. Create a drop-down list box of table styles you would like the “user” to select. You can use the INDEX() function to identify the selected item. (An example has been provided in the screenshot)

Hover your mouse over the table styles to find out a list of styles available

After-Course Sandbox: Streamlining a Process