Читать книгу Excel VBA 24-Hour Trainer - Tom Urtis - Страница 8

Part I
Understanding the BASICs
Lesson 4
Working in the VBE

Оглавление

In Lesson 3, you took a bird's eye view of the Visual Basic Editor, and you became familiar with the names and locations of its most frequently used windows. In this lesson, you navigate through those VBE windows for the purpose of demonstrating how to handle the kinds of maintenance tasks you will often encounter in the VBE.

Toolbars in the VBE

The first thing you may have noticed about the VBE interface is that there is no Ribbon. The traditional VBE menu bar is pretty much the same interface for all versions of Excel since 1997.

Because you will be spending more time in the VBE, you'll want convenient access to the toolbar icons relating to the work you'll be doing. If you have not already done so, press Alt+F11 to get into the VBE, and show the Edit and Standard toolbars whose icons will soon come in handy. From the menu bar at the top of the VBE, click ViewToolbarsEdit and again ViewToolbarsStandard, as depicted in Figure 4.1.


Figure 4.1


Macros and Modules

In Lesson 2, you used the Macro Recorder to create a macro named mySort. You learned how to assign a shortcut key to the macro, and how to enter a brief description of what the macro does. You also learned about a couple of ways to run the macro, by using either the shortcut key or the Macro dialog box. One thing you have not been shown yet is the macro itself, or even how to find it.

Locating Your Macros

When the Macro Recorder created the mySort macro in Lesson 2, it also created a module in which to store the macro. If this module happens to be the first module of the workbook, as was the case for mySort, the Macro Recorder names the new module Module1 by default. If the Macro Recorder creates another module after that and the workbook still holds a module named Module1, the Macro Recorder assigns the default name of Module2, and so on.

In the Project Explorer window, expand the bolded VBAProject title (my Project workbook name is MacroExamples.xlsm) and expand the yellow Modules folder to show the module named Module1. To see the VBA code in that module, you can double-click the module name, or you can right-click the module name and choose View Code, as shown in Figure 4.2.


Figure 4.2


The mySort macro appears in the Code window for Module1. Based on the steps you took while recording the mySort macro in Lesson 2, Figure 4.3 shows the exact code that was produced by the Macro Recorder in Excel version 2003.

NOTE If you record (or manually compose, as you see in later lessons) a macro in a version of Excel after 2003, and you run that macro in a 2003 version, you might experience an error in that code's execution, depending on what the code is trying to do. VBA code plays well together among versions after 2003, but those later versions of Excel contain newer features, such as Sparklines and an updated object model for charts and pivot tables, that a 2003 version would not recognize. VBA code produced by the Macro Recorder in version 2003 usually works just fine in later versions, but be aware that backward compatibility has its limitations when running code in a 2003 version that was produced in a later version.

Figure 4.3


Understanding the Code

All macros start with a Sub statement (Sub is short for Subroutine, commonly referred to as a macro) that includes the name of the macro, followed by a pair of parentheses. For the example macro you see in Figures 4.3 and 4.4, the Sub statement is simply Sub mySort().


Figure 4.4


Because this macro was recorded, there is a series of comment lines below the Sub statement that the Macro Recorder wants you to know about. For example, you see the macro name, the description of the macro you entered into the Record Macro dialog box, and the notation that the shortcut Ctrl+Shift+S has been assigned to this macro.

Comment lines start with an apostrophe, are green in color to help you identify them, and are not executed as VBA code, as opposed to the other lines of VBA code that actually do something when the macro is running.

NOTE The comments you see in a recorded macro directly reflect the information entered in the Record Macro dialog box. For example, if you assign a shortcut key, or you enter text in the Description field of the Record Macro dialog box as shown in Lesson 2, Figure 2.13, that information will be seen as comments in your recorded macro's code, as shown in Figure 4.3.

The remaining lines in the macro are VBA statements, and they represent every action that was taken while the Macro Recorder was on:

1. The first thing you did was select column A.

2. Next, you inserted a new column at column A.

3. Next, you selected column C, cut that column, and pasted it to column A.

4. Next, you went back to select column C because it was empty, and you deleted it.

5. Next, you selected range A1:C13 where the table of data was.

6. Next, you sorted the selected range.

7. Next, you selected range C2:C13, which contained numbers you wanted to format.

8. Next, you formatted the selected cells with the thousands comma separator and no decimal places.

9. Next, you selected range A1:C1 where the column labels were.

10. Next, you formatted the selected range in order to Bold the font of those label cells.

11. Finally, you turned off the Macro Recorder, which produced the End Sub line. All macros end with the End Sub statement.

That's quite a few “Nexts” in the explanation for what is going on! Fortunately, you can edit a macro by typing your own descriptive comments, and you can consolidate a lot of the code so it runs faster and looks cleaner.

Editing a Macro with Comments and Improvements to the Code

As good as the Macro Recorder is at teaching VBA code, it is woefully lacking in the efficiency department with the volume of code it produces. To be fair, the Macro Recorder was never meant to be a lean, mean coding machine. Its primary function, which it performs flawlessly, is to produce VBA code that represents your every on-screen action.

It should be said that there is no law in the universe dictating that you must modify your every recorded macro. Sometimes, for simple macros that do the job, leaving them in their original recorded state is fine – if they work the way you want them to, you've won that round.

However, for the majority of VBA code that gets produced by the Macro Recorder, the superfluous and inefficient nature of its excessive code will be impossible to ignore. Besides, when you send your VBA workbook masterpieces to other users, you'll want your code to look and act beyond the beginner stage of recorded code.

NOTE You will find that editing a macro in the Code window is very similar to editing a Word document. Of course, rules exist for proper syntax of VBA code lines, but the principles of typing text, selecting words and deleting them with the Delete key, pressing Enter to go to the next line down – all these word-processor kinds of behaviors with which you are familiar – will help make the macro edit process an intuitive one.

A rule of thumb in VBA development is, don't select or activate objects unless you need to. The methods of Select and Activate are among the biggest culprits of slow, meandering macro execution. For example, the first two lines of code in the recorded macro are:

Columns("A: A").Select

Selection.Insert Shift:=xlToRight

Those two lines can and should be consolidated into one line, bypassing the Selection activity:

Columns("A").Insert Shift:=xlToRight

Same with the next two statements:

Columns("C: C").Select

Selection.Cut Destination:=Columns("A: A")

which can be expressed more succinctly as:

Columns("C").Cut Destination:=Columns("A")

You can see where I am going with this. In VBA, you can act directly upon most objects, most of the time, without needing to select them. When you deleted column C, you never needed to touch it in order for VBA to do the work for you, because the following statement:

Columns("C: C").Select

Selection.Delete Shift:=xlToLeft

can become this:

Columns("C").Delete Shift:=xlToLeft

Figure 4.4 shows how the original 13 lines of code in the mySort macro have been reduced to a much more readable and highly efficient six lines. Also notice how comments can be added for the purpose of enhancing the organized look of the macro. Your comments will help you, and anyone reading the macro, to understand what the code lines are doing, and why they are doing it.

NOTE You've now seen plenty of comments in the example macros, and how useful comments can be in your VBA code. To enter a comment line of text, simply type the apostrophe character, and everything you type after that, on that same line, will be regarded as a comment and not executed as VBA code. Usually, comments are written as standalone lines of text, meaning the very first character on that line is the apostrophe. However, some programmers prefer to place comments on the same line as actual VBA code. For example:

Range("A1").Clear 'Make cell A1 be empty for the next user.

In any case, comments will be green in color by default, and will not be executed as VBA code.

Another way you can speed up your macros is to use the With statement when you are performing multiple actions to the same object, such as to a range of cells. Suppose as part of your macro you need to clear a range of cells and format the range for the next user. If you use the Macro Recorder to do this, here is the code you might get:

Range("A1:D8").Select

Selection.Clear

Selection.Locked = False

Selection.FormulaHidden = False

Selection.Font.Bold = True

Selection.Font.Italic = True

Notice there are five lines of code that all start with the Selection object, which refers to the selected range of A1:D8. If this code were to run as the Macro Recorder produced it, VBA would need to resolve the Selection object for each line of code.

You can do two key edits to these lines of code by avoiding the Select method altogether and referring to the range object only once at the beginning of a With structure. Between the With and End With statements, every line of code that starts with a dot is evaluated by VBA as belonging to the same range object, meaning the range reference need only be resolved once. Here is the condensed code using a With structure for greater efficiency:

With Range("A1:D8")

.Clear

.Locked = False

.FormulaHidden = False

.Font.Bold = True

.Font.Italic = True

End With

Deleting a Macro

There will be many times when you have recorded or composed a macro that you don't need any more. Instead of having a useless macro hanging around doing no good, it's better to delete it. To delete a macro, you can select its entire code in the Code window (be sure you only select from and including the Sub line to and including the End Sub line) and press the Delete key.

NOTE You can delete a macro from outside the VBE. While on any worksheet, if you press Alt+F8 to call the Macro dialog box, you can select the macro name in the list and click the Delete button.

Inserting a Module

With larger VBA projects, you'll want to distribute your macros among two or more modules. With large projects, you'll be organizing your macros by some kind of theme or purpose. For example, the macros in your company's budget workbook that deal with reports might be placed in their own module. Sometimes you will have no choice in the matter, because modules do have a limit as to how much code they can individually support. To insert a new module, from the VBE menu bar, select InsertModule, as shown in Figure 4.5.


Конец ознакомительного фрагмента. Купить книгу
Excel VBA 24-Hour Trainer

Подняться наверх