You are visitor number since 14 October 2004.
Go to Howard Kaikow's home page
Copyright © 1999 by Howard Kaikow. All rights reserved.
Date: 10 September 1999
From: Howard Kaikow <firstname.lastname@example.org>
Subject: Macro recording is unreliable and not a good way to learn VBA
It is often stated that one way to learn how to use Word VBA is to record macros and examine the resultant code. Unfortunately, one cannot trust the code produced by recording macros. For example:
Word performs certain operations when you issue commands through the user interface that are not reflected in the code recorded for those operations.
One example is using the Edit | Find menu to search for text that is in a, say, header, when the cursor is in the body of the document. Word performs some operations for you which are not included in the recorded code. If you run the recorded macro, and the cursor is not in the appropriate header, the search will fail to find the text in the header.
Sometimes, Word will generate code that is just plain incorrect, even though the operations you request through the user interface will work correctly. My current favorite example may be easily reproduced.
It is not uncommon for a template in the Office Startup directory to include AutoText. To reproduce an example of this problem, try the following:
Include an AutoText in a global template. Let's use UtilitiesAutoText as the AutoText name.
Use the File | New menu to create a new document based on the Normal template.
Turn on the macro recorder and insert the AutoText UtilitiesAutoText into the document. Stop the macro recorder. Do not yet look at the generated macro code.
Now run the generated macro. Obviously, this should again insert the same AutoText. Wrong! Instead, you get an error message indicating that the AutoText name does not exist. How can that be, after all, you just inserted the AutoText and recorded the macro code?
OK, the suspense must be killing you, take a look at the macro code. You should see something like the following:
NormalTemplate.AutoTextEntries("UtilitiesAutoText").Insert Where:= _ Selection.Range
Even though Word carried out the command you requested, the macro recorder generated incorrect code. The AutoText name is not in the Normal template so the code cannot work.
The macro recorder generates very poor code, for example:
Such code will execute much more slowly than most any reasonable manual coding.