Excel VBA 24-Hour Trainer. Tom Urtis
Чтение книги онлайн.

Читать онлайн книгу Excel VBA 24-Hour Trainer - Tom Urtis страница 10

СКАЧАТЬ style="font-size:15px;">      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 СКАЧАТЬ