|
Chapter 1: Make a Macro Do Simple Tasks
Chapter 1: Make Macro Do Simple TasksChapter ObjectivesEstimated time: 40 minutes In this chapter, you'll learn how to:
Last month we lost the remote control to our VCR. It was awful. I wanted to set the machine to record "Mystery Science Theater 3000" at 1:00 a.m. one night, but I couldn't do it because all the scheduling features were built into the remote control. Fortunately, after about two weeks, my wife detected a bulge in the cloth backing of the recliner and retrieved the precious controller. I'm so happy that I can now record old movies. Someday I might even watch some of them. Microsoft Visual Basic for Applications (VBA) is Microsoft Excel 2000's remote control. Sure, you can use Excel without ever using VBA, but not only can the VBA "remote control" make your life more convenient, it also allows you to take advantage of features that you can't get to with the standard "front-panel" controls. And once you become acquainted with Excel's remote control, you'll wonder how you ever got along without it. If you haven't yet installed the practice files that come with this book, refer to "Installing the Practice Files and Additional Microsoft Excel Tools" in the Introduction to this book.
The first spreadsheet macro languages mimicked the user interface. For example, if you typed R (for "Range"), N (for "Name"), and C (for "Create") in the user interface, you would enter RNC into the macro to automate the process. This approach had inherent weaknesses. Not only were keystroke macros difficult to read, but they didn't adapt well to the graphical user interface. What do you use to represent dragging a rectangle with the mouse? To solve these problems, the early versions of Excel contained a new type
of macro language that made the macro commands independent of the user
interface. For example, in Excel version 4 you could copy a range in at least
three different ways: press Ctrl-C, click the Copy toolbar button, and click Copy
on the Edit menu. All those user interface sequences translated to a single
macro function, =COPY(). These function-based macros had two major
drawbacks: First, Excel macros were very specific to Excel; the language couldn't be
adapted to other applications. Second, the number of functions kept increasing with
each new version, and there was no good way to organize or group the thousands
of possibilities.
Excel with VBA incorporates Automation (once known as OLE Automation), a powerful way of automating applications. Excel was the first major application to take advantage of this concept. In this approach, VBA acts as a general-purpose language that's independent of the application. Suddenly, anyone who knows how to work with any version of Visual Basic has a big head start in automating Excel, and anyone who learns how to write Excel macros in VBA can transfer that knowledge to other types of Visual Basic programming. NOTE VBA is a version of Visual Basic that's hosted by an application, such as Microsoft Excel. A VBA macro can't run independently of its host application. VBA and the stand-alone version of Visual Basic both use the same language engine, editor, and most supporting tools. In this book, we'll use "VBA" to refer specifically to the macro language in Excel, and "Visual Basic" to refer to anything that's shared by all versions of Visual Basic.
Even though Excel hosts VBA, VBA doesn't have any special "hooks" into Excel's internals. Rather, Excel exposes its capabilities to VBA by means of a special set of commands called an object library. VBA talks to Excel's object library. VBA can control not only Excel, but also any application that provides an object library. All Microsoft Office applications provide object libraries, and several other Microsoft and non-Microsoft applications do, too. The VBA that comes with Excel isn't the only language that can communicate with the object library. Any language that supports Automation can control Excel. You can control Excel not only with the VBA hosted by Excel, but also with a VBA project hosted by Microsoft Word, with the stand-alone version of Visual Basic, or even with C++ or Inprise Corporation's Delphi program.
Not only does the object library expose Excel's capabilities to VBA, but even more important, the object library exposes Excel's capabilities to you. Once you know how to read and interpret an object library, you can discover new features and figure out quickly how to put them to work. The best way to start finding out about how VBA communicates with Excel's objects is to record some simple macros. Eventually, however, you'll want to move beyond the limitations of the macro recorder. In Part 1 of this book, you'll learn how to record and modify simple macros. In Part 2, you'll learn how Excel objects work. In Part 3, you'll learn some secret powers of Visual Basic for Applications. And in Part 4, you'll learn how to make a macro easy to use. Start the lesson
Creating a Simple MacroExcel has a large collection of convenience tools readily available as shortcut keys and as buttons on toolbars. Sometimes a built-in convenience tool doesn't work quite the way you want. Enhancing a built-in tool is a good first macro to create. Show the Visual Basic toolbarBefore you start creating the macros, take one small step that will make your work with macros much easier.
Now, when you're ready to record a macro, just click the circle on the toolbar. When you're ready to run a macro, click the triangle. Format currency with a built-in toolOn the Formatting toolbar, Excel has a button that formats the current selection as currency: the Currency Style button.
The currency format that Excel applies when you click the Currency Style button has two decimal places. Sometimes you want to display currency with two decimal placesperhaps in your checkbook. But other times you don't want two decimal placesperhaps your budget doesn't warrant that kind of precision. You might want to create a macro to format a cell as currency with no decimal places instead. Record a macro to format currency
A macro name can contain uppercase and lowercase letters, underscores, and periods, but no spaces.
That's it. You recorded a macro to format a selection with the currency format you want. Now you probably want to try out the macro to see how it works. Run the macro
Your macro gives the selected cells your customized currency format. Running the macro from the Macro dialog box isn't much of a shortcut, though. Assign a shortcut key to the macro
IMPORTANT Excel uses many ctrl key combinations as built-in shortcuts. For example, Ctrl-C is Copy and Ctrl-Z is Undo. If you assign one of these shortcuts to your macro, pressing the shortcut runs your macro rather than the built-in command. If you always assign a Ctrl-Shift key combination for your macros, you'll be much less likely to override a built-in shortcut. You can also assign a shortcut key at the time you first record a macro.
Now you've successfully recorded, run, and enhanced a macroall without seeing anything of the macro itself. Aren't you burning with curiosity to see what you've just created? Look at the macroThe macro is actually hidden away in the workbook, but you need to open the Visual Basic Editor to be able to see it.
The window captioned Module1, a module, is the place where the recorder puts macros. Your macro is in the Module1 module. The macro looks like this: Sub FormatCurrency()
'
' FormatCurrency Macro
' Macro recorded 11/15/98 by Reed Jacobson
'
'
Selection.NumberFormat = "$#,##0"
End Sub
For details about number format codes, ask the Assistant for help, using the words "user-defined numeric formats."
The five lines that start with apostrophes at the beginning of the macro are comments. The apostrophe at the beginning of the line indicates that the following text is a comment. (The blank line among the comments, without even an apostrophe, is where the recorder would have put the shortcut key combination if you had assigned it when you recorded the macro.) The recorder puts in the comments partly to remind you to add comments as you write a macro. You can add to them, change them, or delete them as you wish without changing how the macro runs. Comments are green to help you distinguish them from statements that do something. The macro is written in VBA and follows standard Visual Basic rules. The macro itself begins with Sub, followed by the name of the macro. (Is Sub used because a macro is typically hidden, out of sight, like a submarine? Or does it stand for subroutine, for reasons you'll learn at the end of Chapter 2? Stay tuned.) The last line of a macro is always End Sub. The Selection.NumberFormat statement does the real work. It is the body of the macro. Selection stands for "the current selection." NumberFormat refers to an attributeor propertyof the selection. To interpret a VBA instruction, read the statement from right to left, like this: "Let `$#,##0' be the number format of the selection." NOTE Some people wonder why the word NumberFormat comes after the word Selection if you read Selection.NumberFormat as "number format of the selection." In an Excel worksheet, you don't use the English language convention of stating an action first and then the object. ("Copy these cells. Put the copy in those cells.") Instead, on an Excel worksheet you select the object first and then perform the action. ("These cellscopy. Those cellspaste.") Selecting the object first in the worksheet makes carrying out multiple actions more efficient. Macro statements in Visual Basic work backward, the same as actions do in an Excel worksheet. In a macro statement, you state what you're going to work on, and then you do something to it.
The FormatCurrency macro changes a single attribute of the current selectionthe number format. In Excel macros, an attribute is called a property. In the FormatCurrency macro, NumberFormat is a property of a cell. Many macro statements assign a value to a property. Whenever the macro recorder creates a statement containing an equal sign, the word in front of the equal sign is a property. Sometimes when you record an action, the macro changes multiple properties at the same time. Merge text vertically with a commandExcel has a toolbar button that can merge and center several cells in a horizontal row: the Merge And Center button. But sometimes you might want to merge cells vertically along the edge of a report. Excel doesn't have a toolbar button that merges cells vertically along the edge and adjusts the position of text in those cells, but you can record a macro that does. To better understand what's required, first walk through the steps to create this format using menu commands.
Putting a label to the side of a block of cells is extremely powerful. You can make it easy to do by recording a macro. Record a macro to merge cells vertically
TIP To rearrange the windows, minimize all the applications you have open except Excel and the Visual Basic Editor. Then right-click the taskbar, and click Tile Vertically from the shortcut menu.
IMPORTANT If you assign the same shortcut key to two macros, the one that appears first in the Run Macro list is the one that runs. A shortcut key is valid only while the workbook containing the macro is open.
Sub MergeVertical()
'
' MergeVertical Macro
' Merge cells vertically
'
' Keyboard Shortcut: Ctrl+Shift+M
'
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 90
.AddIndent = False
.ShrinkToFit = False
.MergeCells = True
End With
End Sub
The macro shows seven different property settings for the cell alignment. Each property is followed by an equal sign. These properties correspond exactly to the controls you saw in the Format Cells dialog box. Each of the property settings affects the current selection, just as the
Number-Format property setting does in the FormatCurrency macro. In the
FormatCurrency macro, however, the property name is attached directly to
Selection with a period, to show that the property affects the cells in the current selection. In
this macro, however, each property name just "hangs there," preceded only by a period. A pair of statements beginning with With and ending with End With is called a With structure. It means that every time there is a period with nothing in front of it, you pretend that the word that followed the With is there. With structures make the code easier to read because you can tell instantly that all the properties relate to the current selection. You'll often see With structures in macros that you record. Eliminate unnecessary lines from the macroIn many dialog boxes, the macro recorder records all the possible properties, even though you might change the values of only one or two of them. You can make your macro easier to understand if you eliminate unnecessary properties. In the MergeVertical macro, you need to change the values of only the Orientation and MergeCells properties. You can therefore delete the other lines from the macro.
Now you've not only recorded a macro, but you've also deleted parts of itand it still works. Next you'll record a macro and make additions to it. Where Do New Macros Go? The first time you record a macro, Excel creates a new module. Each time you record an additional macro, Excel adds the new macro to the end of the same module. when you close and reopen the workbook, the macro recorder starts recording macros into a new module. There is no way for you to control where the recorder puts a new macro. Having macros in multiple modules shouldn't be a problem. When you use the Macro dialog box to select and edit a macro, it automatically takes you to the appropriate module. A typical Excel worksheet has light gray gridlines that mark the boundaries of the cells. Sometimes, you might want to remove the gridlines. First walk through the process to remove the gridlines with menu commands, and then record a macro to make the change. Remove gridlines with a command
Gridlines are a property of the window. You can select the Gridlines check box so that the value of the property is True and the window displays the gridlines, or you can clear the check box so that the value of the property is False and the window doesn't display the gridlines. Now see how the recorder turns off the gridlines. Record a macro to remove gridlines
Sub RemoveGrid()
ActiveWindow.DisplayGridlines = False
End Sub
This macro is similar to the FormatCurrency macro. You can read it as "Let `False' be the DisplayGridlines property of the active window." This time you're not changing the selection but rather the active window. In both cases, you're changing an object, an Excel element that you can control with macros. However, this time the object isn't a range of cells, but a window. You'll learn more about objects in Part 2.
Run the macro from the Visual Basic EditorYou can easily change the macro to make it restore the gridlines.
TIP If you're in VBA and want to display the Macro dialog box so that you can select a macro, click outside of any macro before you press F5.
Toggle the value of a property with a macroYou could create one macro to turn the gridlines off and a second macro to turn them back on, but somehow, letting a single macro toggle the value of the property seems more natural. To toggle the value of a property, you first ask Excel for the current value, which you can store in a special container called a variable. You then change the value as you assign the variable back to the property. Here's how:
NOTE You can use any name you want as a variable name, but you should avoid names already used by Excel or Visual Basic. If you add a prefix such as my to the variable name, you'll most likely avoid any potential conflict.
TIP If Option Explicit appears at the top of the module, delete it before running this macro.
The macro reads the old value of the property, changes it to the opposite
with the keyword Not, and assigns the newly inverted value back to the property.
By now, you should see a pattern to creating a simple convenience macro: Try out an action interactively. Once you know how to do the task, start the recorder. Do the task with the recorder on. Then stop the recorder. So far, all the macros you've recorded have changed the value of one or more properties of an object. Some actions that you can record don't change the value of a property. Let's see what a macro looks like when it doesn't change a property. Suppose you want to freeze the formulas of some cells in the Budget2000 worksheet at their current values. First change the formulas to values using menu commands, and then create a macro that can change any formula to a value. Convert a formula to a value using menu commands
As you carry out the copy and paste actions with the menus, notice that the Copy command doesn't bring up a dialog box. You see a moving border around the cells and a message in the status bar, but you don't need to tell Excel how to do the copying. The Paste Special command, on the other hand, does require additional information from you to carry out its job, so it displays a dialog box. Some actions in Excel require additional information about how to carry out the action, and some don't. Convert a formula to a value with a macroWatch how the macro recorder handles actions that display a dialog box, compared with how it handles actions that don't.
Sub ConvertToValues()
Selection.Copy
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End Sub
The basic structure of this macro is the same as that of the other macros you've seen in this chapter. The last line, for example, sets the value of the CutCopyMode property in much the same way that the ToggleGrid macro changed the DisplayGridlines property setting of the active window. The two lines that begin with Selection, however, are something new. Neither has a simple equal sign in it. Selection.Copy looks similar to
Selection.NumberFormat from the FormatCurrency macro. In that macro,
NumberFormat was a property of the
selection and you were assigning a new value to the
NumberFormat property. Copy, however, isn't a property. That's why it doesn't have an equal sign after it. You
don't assign anything to Copy; you just do it. Actions that don't use an equal sign
to set the value of a propertythat is, actions like
Copyare called methods. Like the names of properties, the names of methods are recorded by Excel and
displayed at the end of the object's name. PasteSpecial is also a method in Excel. PasteSpecial doesn't have an equal sign after it; it isn't a property that you assign a value to. The Paste Special command on the Edit menu displays a dialog box, but the dialog box doesn't show you properties to change; it just asks how to carry out the paste special action. When you execute the PasteSpecial method in a macro, you give the extra information to the method. The extra pieces of information you give to a method are called arguments. Using a method with an object is like giving instructions to your nine-year-old. With some instructionslike, "Come eat"you don't have to give any extra information. With other instructionslike, "Go to the store for me"you have to tell what to buy (milk), how to get there (on your bike), and when to come home (immediately). Giving these extra pieces of information to your child is like giving arguments to an Excel method. (You call them arguments because whenever you tell your child how to do something, you end up with one.) The four arguments you give to PasteSpecial correspond exactly to the four option groups in the Paste Special dialog box. Each argument consists of a name for the argument (for example, Paste) joined to the argument value (for example, xlValues) by a colon and an equal sign (:=). Don't confuse an argument with a property. When you assign a new value to a property, you separate the value from the property with an equal sign, as in this statement: ActiveWindow.DisplayWorkbookTabs = False You read this statement as "Let `False' be the DisplayWorkbookTabs property of the active window." Assigning a value to a property can appear superficially similar to using a named argument with a method. When you use a named argument with a method, you separate the method name from the argument name with a space, and you separate the argument name from the argument value with a colon and an equal sign. You must never confuse an equal sign with a colon and equal sign, any more than you would confuse beer with root beer. When you have more than one argument, separate each one from the next with a comma and a space, as in this statement: Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone An argument looks a lot like a property, but an argument always follows a method name, whereas a property follows an object. Also, a property is followed by an equal sign, but an argument is followed by a colon and an equal sign. Make a long statement more readableWhen one of the statements in a macro gets to be longer than about 70 characters, the macro recorder puts a space and an underscore ( _ ) after a convenient word and continues the statement on the next line. The underscore tells the macro that it should treat the second line as part of the same statement. You can manually break long statements into several lines, as long as you break the line after a space. You can also indent related lines with tabs, to make the macro easier to read.
Most of the macros in this chapter change the settings of object properties, but this macro executes object methods. Properties and methods look very similar: both are separated from objects by periods. However, you assign new values to properties, whereas you execute methods, sometimes giving the method arguments along the way. Create a personal signatureIncluded with your Microsoft Office 2000 CD is a program that you can use to create a personal signature.
You've now created a personal signature that you can use to sign your macro projects. Signing Personal Macros When you open a workbook that contains a macro, Excel displays a message warning you that macros can contain viruses that can harm your computer. You certainly don't want to see this message every time you open a workbook. One way to avoid the message is to change Excel's security level to Low, but then if someone e-mails you a workbook that happens to contain a macro virus, you wouldn't have any warning at all. If you have Microsoft Internet Explorer version 4 or later installed on your computer (even if it isn't your default browser), you can digitally sign your VBA project to avoid the warning message. Before you can sign a project, you need a digital signature. You might work at a company that can issue you a digital signature, or you can obtain a digital signature from a certificate authority such as VeriSign or Thawte, or you can create a self-signature for your own macros. TIP For information about how to get a digital certificate, ask the Answer Wizard for information using the words "Digital Certificate."
Add a signature to your projectYou add a signature to the VBA project part of your workbook. If a virusor anyone elsechanges the VBA project, the signature becomes invalid. The signature applies only to the VBA project, not to the workbook data, so anyone can change the worksheets without invalidating the signature.
The project in the Chapter1 workbook is now signed. If you need to modify a macro, as long as you do it on the machine that contains your digital signature, VBA automatically reapplies the signature. But no one else can reapply your signature to the project. Trust a signatureNow that you have a workbook containing a signed project, you can tell Excel to trust workbooks that contain macros you have signed.
NOTE When you create your own digital signature, Excel can't be certain that the signature is authentic, so it displays a warning message. If you obtain your signature from a certifying agency, no caution message appears.
Security is important when you create any programs, including macros. Security is especially important when you share applications with others. If you create macros for others to use, you'll probably want to obtain a properly authenticated digital signature to protect your work. Chapter Summary
Preview of the Next ChapterIn the next chapter, you'll learn how to combine small macros to automate whole tasks. You'll also learn how to find and fix problems when your macros don't work quite the way you want.
Microsoft Excel 2000 Visual Basic Fundamentals
Last Updated: Friday, July 6, 2001 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||