Microsoft Office Tutorials and References
In Depth Information
The Macro Recorder
Or you can avoid the Select method altogether and write the code even more efficiently:
.Style = “Comma” .Font.Bold = True
.Font.Italic = True
If speed is essential in your application, you always want to examine any recorded VBA code
closely to make sure that it’s as efficient as possible.
You, of course, need to understand VBA thoroughly before you start cleaning up your recorded
macros. But for now, just be aware that recorded VBA code isn’t always the best, most efficient
About the code examples
Throughout this topic, I present many small snippets of VBA code to make a point or to provide
an example. Often, this code might consist of just a single statement. In some cases, the example
consists of only an expression, which isn’t a valid instruction by itself.
For example, the following is an expression:
To test an expression, you must evaluate it. The MsgBox function is a handy tool for this:
To try out these examples, put the statement within a procedure in a VBA module, like this:
‘ statement goes here
Then put the cursor anywhere within the procedure and press F5 to execute it. Also, make sure
that the code is being executed within the proper context. For example, if a statement refers to
Sheet1 , make sure that the active workbook actually has a sheet named Sheet1 .
If the code is just a single statement, you can use the VBE Immediate window. The Immediate
window is very useful for executing a statement “immediately” — without having to create a
procedure. If the Immediate window isn’t displayed, press Ctrl+G in the VBE.
Just type the VBA statement in the Immediate window and press Enter. To evaluate an expression
in the Immediate window, precede the expression with a question mark ( ? ). The question mark is a
shortcut for Print . For example, you can type the following into the Immediate window:
The result of this expression is displayed in the next line of the Immediate window.