Upload
others
View
21
Download
0
Embed Size (px)
Citation preview
Utilizing Macros in Microsoft® Excel®
Presented By:
This manual was created for online viewing. State specific information in this manual is used for illustration and is an example only.
mail: P.O. Box 509 Eau Claire, WI 54702-0509 • telephone: 866-352-9539 • fax: 715-833-3953email: [email protected] • website: www.lorman.com • seminar id: 401009
Dennis TaylorTaylor Associates
Take advantage of this special offer for $50 off of a Lorman
live webinar!
C O N V E N I E N T:Lorman offers a wide variety of live webinars covering current issues affecting numerous industries. Learn the latest on legal compliance, cost savings and strategies, and business trends.
E X P E R I E N C E D :Learn about today’s hot topics presented by our expert speakers who represent prominent firms and have years of industry experience and knowledge.
C U R R E N T :In today’s business world, staying current of the ever-changing regulations is absolutely necessary in order to advance in your field. Earn continuing education credits, educate your entire team and ask questions of the speakers. For a complete listing of upcoming live webinars visit www.lorman.com.
SPECIAL OFFER
$50 OFFYOUR NEXT Discount Code Y1719669This offer can not be used in combination with other discounts.
LIVE WEBINAR
Utilizing Macros in Microsoft® Excel®
©2017 Lorman Education Services. All Rights Reserved.
All Rights Reserved. Lorman programs are copyrighted and may not be recorded or transcribed in whole or part without its express prior written permission. Your attendance at a Lorman seminar constitutes your agreement not to record or transcribe all or any part of it.
Full terms and conditions available at www.lorman.com/terms.php.
This publication is designed to provide general information on the topic presented. It is sold with the understanding that the publisher is not engaged in rendering any legal or professional services. The opinions or viewpoints expressed by faculty members do not necessarily reflect those of Lorman Education Services. These materials were
prepared by the faculty who are solely responsible for the correctness and appropriateness of the content. Although this manual is prepared by professionals, the content and information provided should not be used as a substitute for professional services, and such content and information does not constitute legal or other professional
advice. If legal or other professional advice is required, the services of a professional should be sought. Lorman Education Services is in no way responsible or liable for any advice or information provided by the faculty.
This disclosure may be required by the Circular 230 regulations of the U.S. Treasury and the Internal Revenue Service. We inform you that any federal tax advice contained in this written communication (including any attachments) is not intended to be used, and cannot be used, for the purpose of (i) avoiding federal tax penalties imposed by
the federal government or (ii) promoting, marketing or recommending to another party any tax related matters addressed herein.
mail: P.O. Box 509 Eau Claire, WI 54702-0509 • telephone: 866-352-9539 • fax: 715-833-3953email: [email protected] • website: www.lorman.com • seminar id: 401009
Prepared By:Dennis Taylor
Taylor Associates
MICROSOFT and EXCEL are registered trademarks of Microsoft Corporation and this event is not sponsored by or affiliated with Microsoft Corporation.
Learn What You Want, When You Want From Our Entire
Course Library
UNLIMITED ACCESS
ON-THE-GO LEARNING
We Offer Accredited Training Including CLE, CPE, HRCI, ENG and Many More
A L L - A C C E S S P A S SLORMAN EDUCATION SERVICES
Learn at Your Own Pace From Your Computer,
Tablet or Mobile Device
lorman.com/pass
GET CERTIFIED
Want to learn more? Contact a Lorman
All-Access Pass Specialist:
[email protected] or call 1-877-296-2169
Mastering Microsoft Excel Macros1
In this seminar, you will learn:
Why you’ll need (and want) to use macros
How you can record a macro in a few simple steps
How you can store macros in your own personal workbook
How to quickly run a macro with a keystroke shortcut
How to rapidly access a macro from a button on the Quick Access Toolbar
The basics of VBA – the programming language behind every macro
How to edit macro code
1
2
Why you need macros2
As you work with Excel, you may find yourself repeating the same sequence of commands and actions, for example:
updating sales figures on multiple worksheets
plotting latest monthly data on a chart
applying special formats
locating cells with formulas or cells with values
re‐configuring a mailing label address layout into a database layout
With a macro, you can store these sets of procedures and not need to repeat the entire sequence of actions each time you need them performed.
You will save a lot of time and effort and improve accuracy by creating macros
Sample Short Macros3
Apply a special numeric format that has no toolbar button equivalent
Use a special format for displaying values in millions
Print a selected area
Create subtotals for a group of cells
Turn double accounting underlining on or off.
Select all cells within a selected range that are blank
Round cell values on the actual cells instead of writing/copying formulas and using additional columns
Hide a row if values exceed a certain amount
3
Multi-step Macros4
Remove records of employees whose termination date has passed. Append these records to an archival database Sort the database by department and name Create summary totals by department Print the list showing the detail and summary together Collapse the list and print just the summary Remove the subtotals and sort the full database by employee name and print Sort the database by date of hire and print those results
A macro that performs a series of tasks might resemble this sequence of actions for updating an HR database list twice a week
How do you create a Macro?5
There are three major ways to create a macro
Record the various commands and keystrokes that comprise the tasks you want to automate. These actions get translated into the coding language VBA
Type macro code using VBA – Visual Basic for Applications
Copy macro code from existing macros or from Help screens
The recording method is the dominant technique for creating macros, but it does not cover all possible actions you want a macro to perform
You’ll need to type certain macro statements that have no equivalent recording method; structures such as Do Loops, For Statements, and If…Then…Elsestructures, must be typed or copied into your macro code
With some macros, you’ll use a combination of all three techniques
4
Steps to record a macro6
1. Click the drop arrow below the Macros button on the View tab in the Ribbon
2. Click Record Macro
3. Provide a macro name –a) no spacesb) cannot begin with a numberc) use the underscore character or uppercase
letters to simulate word breaksd) limited to 255 characters.
4. If desired, provide a shortcut key combination.
All combinations automatically use the Ctrl key. Hold down the Shift key to create a combination such as Ctrl+Shift+G as a shortcut.
Avoid lowercase letters so as to not replace commonly used shortcuts such as Ctrl+c for Copy and Ctrl+v for Paste
Steps to record a macro - continued7
5. Select a location to store the macro. Store in This Workbook if you intend to use it only in the current workbook.Store in Personal Macro Workbook if you want it to be available in any workbook.
6. Type a description of what the macro does. Not critical, but helpful – to you and to others.
7. Click OK to begin recording
5
Record your actions8
Perform all the actions that youwant stored in the macro
When finished recording, click the droparrow below the Macros buttonon the View tab in the Ribbon
Click Stop Recording
Steps to record when creating a macro that adds color to all worksheet cells with values:
• Click the Home tab in the Ribbon• Click the Find and Select button in the
Editing group• Click Go To Special• Click the Constants button• Uncheck the boxes for Text, Logicals,
and Errors• Click OK• Click the Fill Color Button in the Font
group on the Home tab of the Ribbon• Click a color• Click any cell
Some macros require typing code9
Record a macro to toggle Double Accounting Underline on or off
Only two steps can be recorded:1. Turn Double Accounting Underline off2. Turn Double Accounting Underline on
Additional code – "if " logic – must be typed or copied from another macro
Demo of how to build this macro
6
Some macros perform complicated lengthy tasks rapidly
10
A macro to transpose data in mailing label layout into Excel database (list) layout
Although mostly created by recording, this macro, too, requires adding additional code to automate a basic procedure so that it gets performed many times.
This macro is representative of those kinds of macros that handle huge amounts of data; it performs a repetitive task with amazing speed.
The Personal Macro Workbook11
The Personal Macro Workbook does not exist until the first time that you store a macro there; Excel then creates this file. Upon a normal exit from Excel, a prompt asks you to save this workbook.
The Personal Macro Workbook, once created, is a hidden workbook that is always open (but usually hidden) when Excel is running.
There is usually no reason to unhide this file.
Any macro stored here is always available because this workbook is automatically opened very time you start Excel
7
Five different ways to run a macro:12
1. From the Macros button on the View tab2. With a keystroke combination that you previously defined
3. From a new button you placed on the Quick Access Toolbar4. From a graphic object, ClipArt, or picture placed on your worksheet5. After activating the Developer tab in the Ribbon, select the Macrosbutton in the Code group of the Developer tab.
Methods 2 and 3 are ideal for Personal Macro Workbook macros. Method 4 is best for macros designed for a specific workbook.
Assign a macro to the QAT(Quick Access Toolbar)
Right‐click the QAT and select Customize Quick Access Toolbar
Click the arrow to the right of Popular Commands and click Macros
From the list of macros, click the macro to be associated with the new button
Click the Add button and then the Modify button
Click one of the 181 buttons in the Modify Button dialog box
Click OK twice
13
8
Run a macro from a ClipArt image
Click the Insert tab in the Ribbon
Click Picture or ClipArt
Browse folders to locate a picture or use the ClipArt dialog box to locate an image
Double‐click the desired picture or image
Right‐click the image and select Assign Macro
Double‐click the name of the macro to be represented by the button
14
The Visual Basic Editor
Press Alt+F11 to get to the Visual Basic Editor
VBA Project Explorer occupies most of the left side
The Code window occupies most of the right side
You might also see these windows: Properties ‐ lower left corner
Watch ‐ lower right corner
Mostly, your focus is on the Code window and the Project Explorer window
Press Alt+F11 to go back to the Excel environment
15
9
Visual Basic Code
Macro code has syntax and rules, like speaking languages
Most macros contain code generated by recording, so you have some idea how to read the code if you recorded the macro
A macro begins and ends with the word Sub
The single quote character and everything to the right of it on a line is a comment. These lines are automatically green.
Other lines comprise the executable code of the macro
16
Running a Macro in Step Mode
To run a macro step by step:1. Click in the macro code and press the F8 key2. Press F8 to step to the next line of code – the code line is highlighted in yellow3. Press the Reset button to stop the macro at any point; Press the F5 key to complete the remaining
steps without stopping.
To see both the macro code and the Excel screen together, use the Restore button in the upper right corner of each application and then resize each application's window to about half the screen. Then you can observe the effects of the macro in the worksheet as you step through the code.
10
Make a macro interactive18
To make a macro more flexible, such as allowing it to prompt for user input, you can type the VBA statement InputBox into a macro, as in this example which prompts the user to type a sheet name. The macro then activates that sheet and process the data there.
SheetName = InputBox("SheetSelector", "Type sheet Name")
Worksheets(SheetName).Activate
19
Sub ConvertToDB()Range("B1").SelectActiveCell.Range("A1:A6").Select
Do Until IsEmpty(ActiveCell)Selection.CopyActiveCell.Offset(0, 2).Range("A1").SelectSelection.PasteSpecial Paste:=xlPasteAll,
Transpose:=TrueActiveCell.Offset(6, -2).Range("A1:A6").Select
Loop
Columns("D:I").SelectSelection.Sort Key1:=Range("D1"), Order1:=xlAscending,
Header:=xlGuess, _OrderCustom:=1, DataOption1:=xlSortNormal,
Orientation:=xlTopToBottomRange("C1").Select
End Sub
Conversion Macro
11
12
Notes