
Tips.Net > WordTips Home > Macros > Making Macros Run Faster
Summary: Designing a macro to make it run faster. (This tip works with Microsoft Word 97, Word 2000, Word 2002, and Word 2003.)
Macros, once they are running right, can make our life easier. (If they aren't running right, life is definitely not easy.) If you have a macro that does a lot of work for you, you may be interested in trying to make it run faster.
The first task to do, of course, is to examine the macro and see if your algorithms (the way you decided to do things) are as efficient as they can be. Once you are satisfied that they are, you can also speed up your macros by simply putting multiple statements on the same line. Consider the following simple macro, which finds the previous occurrence of something in a document:
Sub PrevFind()
With Selection.Find
.ClearFormatting
.Forward = False
.Wrap = wdFindAsk
.Execute
End With
End Sub
This macro is very straightforward. When you save the macro, the statements it contains are parsed down to three-byte tokens that can be run more efficiently by VBA. (You never see the tokens; you only see the macro-language equivalent of the tokens.) When the macro is running, the VBA command processor grabs one line at a time and executes all the tokens on that line. Thus, in the foregoing there are eight lines that are individually fetched and executed by the processor.
Now consider the following version of the same macro:
Sub PrevFind() With Selection.Find .ClearFormatting: .Forward = False: .Wrap = wdFindAsk: .Execute End With: End Sub
This version seems much shorter because individual lines have been concatenated and separated with a colon. This decreases the readability of the macro, but it increases the speed at which it will execute. Why? Because the VBA command processor still grabs a line at a time to process. In this instance, there are only four lines to grab. Less "grabbing time" means that execution is faster. The third line of this macro, which used to occupy four lines, is now processed as a single line.
Putting multiple statements on the same line does decrease the readability of a macro. Depending on your needs, however, this could be a fair tradeoff for the speed increase you may achieve. You will need to try this technique in your own macros to see if it makes sense for you.
Tip #1640 applies to Microsoft Word versions: 97 2000 2002 2003
Save Time! You can have this tip (and several hundred just like it) in the WordTips annual archives. Imagine having over 400 tips available at your fingertips, in each annual volume.
Learn to use styles and you discover the real power behind Word. Fast, easy, consistent document formatting and updating is within your grasp. (more information...)
Ask a Word Question
Make a Comment
Beauty Tips
Car Tips
Cleaning Tips
College Tips
Cooking Tips
Excel2007 Tips
ExcelTips
Family Tips
Gardening Tips
Health Tips
Home Tips
Money Tips
Pet Tips
Word2007 Tips
WordTips