14
Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in the worksheet and translates them into the VBA language. You do not have to hurry when you record a macro. The recorder records your actions, but not the time you take to perform them. Planning your actions and performing them carefully and in a logical order is more important than performing them quickly, because every mouse click, cell selection, and cell entry is recorded. If you make a mistake, either deleting the macro and recording it again, or opening the finished macro and editing your mistakes, is easy to do. Because the recorder is limited to recording only the actions you perform, not all procedures can be written using this method alone. For example, the recorder cannot create a complex macro that repeats specific actions until a particular condition is met, or display a custom dialog box to take user input. On the other hand, the macro recorder is very useful for quickly recording many actions that you can edit manually to make them even more useful, or copy and paste into longer procedures that require additional written procedure code. The recorder is also a very useful method for learning the Visual Basic for Applications (VBA) language because you can record your actions, and then look at the VBA code the recorder wrote. Macro Storage All macros are stored in workbooks. When you record a macro, you must choose a storage workbook. You have three options for macro storage. When you record a macro, you can choose to store the macro in This Workbook, in a New Workbook, or in the Personal Macro Workbook. Store the procedure code for a macro somewhere that is easily accessible. Y ou can record macros to automate tedious and repetitive tasks in Excel without writing programming code directly. Macros are efficiency tools that enable you to perform repetitive or tedious actions quickly with a single keystroke or button click. A macro can be very short. For example, by using the macro recorder and a little quick editing, you can create a one-line macro that turns fixed-decimal entry on or off with a single button click. Without a macro, the same procedure requires five button clicks. A macro can also be quite lengthy. You can record a macro to format and summarize some data, set up charts to present the data, and finally print the data. A single macro can do all of this with one click of a button, and much more rapidly than you can do it yourself. 4 4 COPYRIGHTED MATERIAL

Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

  • Upload
    others

  • View
    15

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Introduction to Macros

Macro RecorderThe macro recorder works just like a tape recorder.When you turn it on, it records all of your actions inthe worksheet and translates them into the VBAlanguage. You do not have to hurry when you recorda macro. The recorder records your actions, but notthe time you take to perform them. Planning youractions and performing them carefully and in a logicalorder is more important than performing themquickly, because every mouse click, cell selection, andcell entry is recorded. If you make a mistake, eitherdeleting the macro and recording it again, oropening the finished macro and editing yourmistakes, is easy to do.

Because the recorder is limited to recording only theactions you perform, not all procedures can bewritten using this method alone. For example, therecorder cannot create a complex macro that repeatsspecific actions until a particular condition is met, ordisplay a custom dialog box to take user input. Onthe other hand, the macro recorder is very useful forquickly recording many actions that you can editmanually to make them even more useful, or copyand paste into longer procedures that require

additional written procedure code. The recorder isalso a very useful method for learning the Visual Basicfor Applications (VBA) language because you canrecord your actions, and then look at the VBA codethe recorder wrote.

Macro StorageAll macros are stored in workbooks. When yourecord a macro, you must choose a storageworkbook. You have three options for macro storage.When you record a macro, you can choose to storethe macro in This Workbook, in a New Workbook, orin the Personal Macro Workbook. Store the procedure

code for a macro somewhere thatis easily accessible.

Y ou can record macros to automate tediousand repetitive tasks in Excel without writingprogramming code directly. Macros are

efficiency tools that enable you to perform repetitiveor tedious actions quickly with a single keystrokeor button click. A macro can be very short. Forexample, by using the macro recorder and a littlequick editing, you can create a one-line macro

that turns fixed-decimal entry on or off with a singlebutton click. Without a macro, the same procedurerequires five button clicks. A macro can also be quitelengthy. You can record a macro to format andsummarize some data, set up charts to present thedata, and finally print the data. A single macro can doall of this with one click of a button, and much morerapidly than you can do it yourself.

44

05_579738 ch01.qxd 1/19/05 1:30 PM Page 4

COPYRIG

HTED M

ATERIAL

Page 2: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Store Macros in This WorkbookThis Workbook stores macros in the currently activeworkbook, making them available to use in all openworkbooks as long as this workbook is open. This isa good option to choose if you want to share themacro with other users, or if you want to send anautomated workbook application with its macros toanother user. When you send the workbook, itsmacros go with it.

Store Macros in the New WorkbookIf you store a macro in New Workbook, Excel createsa new workbook and the macro stored there is onlyavailable when that workbook is open. This is usefulif you want to create a new workbook to beginbuilding an application, or create a new workbookjust to store specific groups of macros, such asfinancial or budget macros.

Store Macros in the PersonalMacro WorkbookA macro stored in the Personal Macro Workbookis always available to any workbook you haveopen. The Personal Macro Workbook is namedPERSONAL.XLS and is saved in the XLSTART folderin your Microsoft folders. It always opens butremains hidden when Excel starts, so you never seeit unless you unhide it. The first time you store amacro in the Personal Macro Workbook, Excelcreates the workbook; every time you store anothermacro in the Personal Macro Workbook, the macrois added to the existing Personal Macro Workbook.These macros are only available in your copy ofExcel. They do not travel with other workbooks yousend to other users.

Recording Simple Macros

5

chapter1P

AR

TI

5

05_579738 ch01.qxd 1/19/05 1:30 PM Page 5

Page 3: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Record a MacroY ou can save time by using the macro recorder and

letting Excel write much of your programmingcode for you. You can also become familiar with

the programming language more quickly by looking at theprocedure code the macro recorder writes for the actionsyou perform.

When you record a macro, give the macro a recognizablename. Macro names must begin with a letter and arelimited to 255 characters. The names cannot have spaces,but they can have letters, numbers, and underscore (_)characters. Names such as MakeBold and ToggleDecimalare good examples.

You must select a workbook in which to store the macro.The macro can run in any workbook as long as theworkbook where the macro is stored is open. The PersonalMacro Workbook is a hidden workbook that opens whenyou open Excel, so any macros you store in the PersonalMacro Workbook are always available.

You can create an optional shortcut key to run the macro,and in the Description box add a comment to the macrothat does not affect the macro actions. You can delete thedescription or enter a different description that moreaccurately describes what this macro does if you want to.

1

6

2

4

7

5

3

This Workbook

1 Click Tools.

2 Click Macro.

3 Click Record New Macro.

6

Record a Macro

The Record Macro dialog box appears.

4 Click in the Macro name field and type aname for the macro.

5 Click in the Shortcut key box and type a letterif you want to create a shortcut key.

6 In the Store macro in box, click and selecta workbook in which to store the macro.

7 Click OK.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 6

Page 4: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

How can I test the recorded macro?

You can test the macro immediatelyby using the shortcut key or themacros dialog box. To use theshortcut key, set up a worksheet torun your macro and press the macroshortcut key. To use the macro dialogbox, set up a worksheet to run yourmacro. From the menu, click Tools,Macro, and then Macros. In theMacros dialog box, select the macroname from the Macro name list andthen click the Run button.

How can I record the macro to runin any cells I choose rather than thesame cells every time?

If you select cells after you start themacro recorder, that cell selection isrecorded. To run in any cells youselect, select cells before you start themacro recorder, and then start therecorder and record your actions. Forexample, if you want to recordentering a formula, select a cellbefore you start the recorder, andthen record entering the formula.

The Stop Recording toolbar appears. Themacro recorder is recording all your actions.

8 Perform the actions you want the macroto perform.

In this example, the Bold button ( )is clicked and the selected cells areformatted bold.

9 Click the Stop Recording button ( ).

PA

RT

I8

9

Recording Simple Macros

7

chapter1

The Stop Recording toolbar disappears,and your macro is recorded.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 7

Page 5: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Record a Macro to Turnon Decimal EntryR ecording a macro that turns on the Fixed Decimal

setting is an efficiency tool because it does in one-step what would normally take five. Because it is

stored in the Personal Macro Workbook, the macro isalways available to any workbook.

If you enter fixed-decimal numbers in a worksheet, such asprices or expenses, you find yourself typing the decimalpoint repeatedly. Excel enters the decimal pointautomatically if you turn on the Fixed Decimal setting,enabling you to type the numbers without having to typethe decimal points.

After you run the macro, type a number in a cell. Thenumber is entered with fixed decimals even though you didnot type a decimal point.

After the macro turns the Fixed Decimal setting on, youmust either turn it off manually or create a second macro toturn it off for you. You can make this second macro evenmore efficient by making it a toggle, which turns the FixedDecimal setting on and off with the same single keystrokeor button click. To make the macro a toggle, see thesection “Edit a Macro to Make It a Toggle.”

1

6

2

4

7

5

3

Personal Macro Workbook

1 Click Tools.

2 Click Macro.

3 Click Record New Macro.

8

Record a Macro to Turn on Decimal Entry

The Record Macro dialog box appears.

4 Click in the Macro name field and type anidentifiable name for the macro.

5 Click in the Shortcut key box and type a letterfor the Shortcut key.

6 In the Store macro in box, click and selectPersonal Macro Workbook.

7 Click OK.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 8

Page 6: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

What if I want three decimal placesinstead of two?

The macro only records the clicking ofthe check box. If you change the FixedDecimal setting in the Edit dialog boxto 3, the macro turns on three decimalplaces when you run it. Then from themenu, click Tools and Options. Selectthe Edit tab again and turn the FixedDecimal setting off. The macro usesthe changed setting.

How can I make this macro easier torun?

You can attach this macro to a customtoolbar button or menu item, whichmakes the macro available in anyworkbook, or you can attach themacro to a graphic object in a specificworkbook and run it by clicking theobject. Because this macro turns on anExcel setting, the fixed decimal entry isturned on in all workbooks until youturn it off again. See Chapter 2 toassign macros to buttons, menus, andgraphical objects.

The Stop Recording toolbar appears, and themacro recorder is recording all your actions inthe workbook.

8 Click Tools.

9 Click Options.

PA

RT

I

8

9

!

@

#

0

Recording Simple Macros

9

chapter1

The Options dialog box appears.

0 Click the Edit tab.

! Click the Fixed Decimal check box to select it ( changes to ).

@ Click OK.

# On the Stop Recording toolbar, click to stoprecording.

The Stop Recording toolbar disappears, and yourrecorded macro turns on fixed-decimal entry.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 9

Page 7: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Open a MacroY ou can open a macro to see and edit the code the

recorder wrote for the actions you performed.Macros open in the Visual Basic Editor. The Visual

Basic Editor is a separate program from Excel. The Excelprogram window remains open behind the Visual BasicEditor program window. You can switch between the twoopen programs by clicking the program buttons on theWindows taskbar at the bottom of your screen.

You can edit an open macro to change what it does, makeit easier to read, and simplify macro statements so themacro runs faster. You can also add code that is notrecordable, such as loops.

When you open a macro, you see a procedure that beginswith the keyword Sub, followed by the macro name and anempty set of parentheses, all on the first line. The codeends with the keyword End Sub. The statements, which arethe lines in between the Sub line and the End Sub line, arethe programmed actions in the macro. The greenstatements preceded by an apostrophe are informationalcomments entered by the macro recorder.

1

3

5

2

4MakeBold

1 Click Tools.

2 Click Macro.

3 Click Macros.

10

Open a Macro

The Macro dialog box appears.

4 Click the name of the macro youwant to see.

5 Click Edit.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 10

Page 8: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

How can I open a macro in the Personal MacroWorkbook?

The Personal Macro Workbook is a hiddenworkbook, and you cannot open a macro usingthe Macro dialog box unless you unhide theworkbook. To unhide the Personal MacroWorkbook, click Window and then click Unhide.Click PERSONAL.XLS and then click OK. ThePERSONAL.XLS workbook appears on your screen,and you can open macros using the Macro dialogbox. Hide the Personal Macro Workbook againwhen you finish so it continues to open and runhidden in the background when you start Excel.To hide it, click Window, then click Hide.

Are there any other ways to open a macro?

Yes, there are three more ways to open the VisualBasic Editor and look at a macro. You can clickTools, Macro, and then Visual Basic Editor; you canpress Alt+F11; or you can click the Visual BasicEditor button on the Visual Basic toolbar. All ofthese methods open the Visual Basic Editor to thedisplay it had when it was last closed. Thesemethods also work in the Personal Macro Workbookwithout unhiding it.

The Visual Basic program window opens toshow the macro you selected.

• The name of the macro is in the Sub line atthe top of the code window.

• The procedure code you recorded iseverything between the Sub line and theEnd Sub line.

6 Click the Close button ( ).

PA

RT

I•

•6

Recording Simple Macros

11

chapter1

You can also click File and then click Closeand Return to Microsoft Excel.

The Visual Basic Editor window closes and youreturn to the Excel window.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 11

Page 9: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Edit a Macro to Make It a ToggleI f you create a macro for a feature that has two

settings, you can edit the macro to enable a user totoggle the setting on and off as needed. Creating a

single macro that acts as a toggle is not a process you cando by recording. However, you can record the initialprocedure to get the structure in place quickly, and thenedit the macro to make it a toggle.

To make a macro a toggle, you use a keyword, a word Excelunderstands, to change a setting in the workbook or theprogram. The keyword for a toggle is Not. The Not

keyword tells Excel that whatever the current value of thissetting is, make the new setting not that value. In otherwords, if the setting is currently True, change it to False,and if the setting is currently False, change it to True.True is the VBA word for “on,” and False is the VBA wordfor “off.”

To edit a macro, you need to open the Visual Basic Editor.To open the Visual Basic Editor, see the section “Open aMacro.”

4

5

2

3

6

1 Open the Visual Basic Editor to displayyour macro code.

The statement to edit is the line thatends in = True or = False.

2 Select the statement object.

3 Click the Copy button ( ).

4 Delete the keyword True.

12

Edit a Macro to Make It a Toggle

5 Type the keyword not in place of theword True.

6 Click Paste ( ).

05_579738 ch01.qxd 1/19/05 1:30 PM Page 12

Page 10: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Why did my keyword not turn blue and getcapitalized?

If a keyword is spelled incorrectly, Excel does notcapitalize it or turn it blue. That is an indication thatyou misspelled the keyword. The same is true fornames, objects, properties, and any other wordsthat Excel should recognize. All Excel keywords andcode words use capital letters, so using capitalletters in names is a good practice. Then, if you typeall code in lowercase, you can find misspellingseasily because Excel does not capitalize the word.

Is there a more efficient way to run my togglemacro?

Yes, attaching the macro to a button for launchingis more efficient, so you do not have to remember akeystroke or take the extra steps to open the Macrodialog box. If the macro changes an Excel settingsuch as the fixed decimal entry, you can make themacro quick to use in any workbook by assigning itto a custom toolbar button and displaying thebutton on your Standard toolbar.

The copied phrase is pasted after thekeyword.

7 Press Enter or click away from thestatement.

The keyword is capitalized and blue.

PA

RT

I

8

9

7

Recording Simple Macros

13

chapter1

8 Click File.

9 Click Close and Return to MicrosoftExcel.

The Visual Basic Editor closes.

The macro toggles the settingbetween on and off every timeyou run it.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 13

Page 11: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Delete a MacroY ou can eliminate clutter from your macro list by

deleting the macros you no longer need. Then youcan quickly select the macro you need without

scrolling through an extensive list of macros.

When you delete a macro, Excel removes the macro so youcan no longer run it, but changes made by that macro areunaffected. For example, if your macro created a worksheettemplate, all the worksheet templates already created bythe macro remain unchanged.

You can delete a macro quickly by opening the Macrodialog box and deleting the macro name. If you select AllOpen Workbooks in the Macros in box, all the macro

names in all open workbooks can be deleted. However, ifyou try to delete a macro in the Personal Macro Workbook,you see a message that says you must first unhide thePersonal Macro Workbook. To delete a macro from thePersonal Macro Workbook through the Macro dialog box,see the section “Delete a Macro in the Personal MacroWorkbook.”

You can also delete a macro from within the Visual BasicEditor code window. You can delete macros from thePersonal Macro Workbook without revealing (unhiding)them if you use the code window.

1

3

5

2

4MakeBold

1 Click Tools.

2 Click Macro.

3 Click Macros.

14

Delete a Macro from the Macro Dialog Box

The Macro dialog box appears.

4 Click the name of the macro.

5 Click Delete.

6 If queried whether you want to delete themacro, click Yes.

The macro deletes.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 14

Page 12: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Will my toolbar button or menu still run themacro after I delete it?

No. When you delete a macro, your toolbar buttonsand menu commands retain the macro assignment.When you click the button or menu command, youget an error message that says the macro cannot befound. To remove a non-functional menu commandor toolbar button, click Tools and then clickCustomize. While the Customize dialog box is open,drag the button or menu command away from thetoolbar or menu bar and drop it on the worksheet.Then click Close in the Customize dialog box.

Can I get a macro back after I delete it?

No. When you delete a macro, it is gone, which iswhy you are queried before deleting. You can savemacro code in a text file by exporting the entiremodule, or you can save the macro code bycopying the code and pasting it into any text file,such as Windows Notepad or Word. You can get themacro back by copying and pasting the code into amodule, or by importing an exported module.

1 Open the macro in the Visual BasicEditor.

Note: To open the Visual Basic Editor,see the section “Open a Macro.”

2 Select the entire macro, from theSub line to the End Sub line.

PA

RT

I

2

Recording Simple Macros

15

chapter1

3 Press Delete.

The macro deletes.

Delete a Macro from the Code Window

05_579738 ch01.qxd 1/19/05 1:30 PM Page 15

Page 13: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Delete a Macro in the PersonalMacro WorkbookY ou can delete the macros in your Personal Macro

Workbook quickly if you first unhide the PersonalMacro Workbook. The Personal Macro Workbook

is always hidden when you start Excel, and Excel doesnot allow you to delete macros from hidden workbooksthrough the Macro dialog box.

The Personal Macro Workbook is created the first timeyou store a macro in it. It exists to hold macros that arealways available to any workbook. Macros that are storedin the Personal Macro Workbook are always displayed inthe Macro dialog box as PERSONAL! followed by themacro name.

If you try to delete a macro in the Personal MacroWorkbook through the Macro dialog box, you see amessage that says you must first unhide the Personal MacroWorkbook. After you delete the macro, you should hide thePersonal Macro Workbook again so that it continues toopen hidden and run in the background when you startExcel. If you do not hide it, the Personal Macro Workbookcontinues to open and display every time you start Excel.By hiding it, you eliminate clutter in your Excel window andany chance of making unwanted changes to the PersonalMacro Workbook.

1

2

3

4

PERSONAL.XLS

1 Click Window.

2 Click Unhide.

16

Delete a Macro in the Personal Macro Workbook

The Unhide dialog box displays alist of open, hidden workbooks.

3 Click PERSONAL.XLS.

4 Click OK.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 16

Page 14: Introduction to Macros Y - Wiley...Introduction to Macros Macro Recorder The macro recorder works just like a tape recorder. When you turn it on, it records all of your actions in

Can I delete a macro from the Personal MacroWorkbook in the code window?

Yes, and you do not need to unhide the PersonalMacro Workbook. Open the Visual Basic Editor.All macros in all open workbooks, including thePersonal Macro Workbook, are available. In theProject Explorer window, expand the VBAProject(PERSONAL.XLS) project, and then expand theproject’s Modules. Double-click the module thatcontains the macro. Then select all the macro text,including the Sub and End Sub lines, and delete it.See the section “Delete a Macro” for the steps.

I deleted my Personal Macro Workbook. How canI get it back?

You can get the Personal Macro Workbook backfrom the Windows Recycle Bin if you have notemptied the Recycle Bin since you deleted theworkbook. Open the Recycle Bin, right-click thePERSONAL.XLS file, and click Restore. The workbookis returned to the XLSTART folder. If you alreadyemptied the Recycle Bin, you cannot get theoriginal Personal Macro Workbook back, but youcan create a new one by recording a macro andstoring it in the Personal Macro Workbook.

The Personal Macro Workbook is unhiddenand displayed in the Excel window.

5 Click Tools.

6 Click Macro

7 Click Macros.

PA

RT

I

5

7

9

!

@

6

8FixedDecimal

Recording Simple Macros

17

chapter1

The Macro dialog box appears.

8 Click the name of the macro.

9 Click Delete.

0 When asked if you want to delete the macro,click Yes.

! Click Window.

@ Click Hide.

The macro deletes. The Personal MacroWorkbook is safely hidden again.

05_579738 ch01.qxd 1/19/05 1:30 PM Page 17