Exploring Object Models with the Object Browser Cleaning Up Recorded Macro Code
Dec 05

Last week we explored the capabilities of the Visual Basic Editor’s (VBE) Object Browser. In addition to a comprehensive listing of all programmable elements in a library, you can use it to search for items, navigate to related help topics, and navigate to related classes and libraries.

This week we’ll examine what you can do with the Locals windows. Together, the Object Browser and Locals windows are useful for investigating and learning various object models that you’ll use.

The difference is that the Locals window is something you use when you are debugging a procedure for displaying the properties associated with a variable that you have defined in your procedure. An example of the Locals window is shown in Figure 1.

Figure 1: Using the Locals window to explore the properties of a variable.

n32progfig1.jpg
Figure 1 - Using the Locals window
to explore the properties of a variable
Click to enlarge

The cool thing about the Locals window is that not only does it show you the properties associated with a given variable, but it also displays the current value of each property. This can be invaluable when debugging. The basic use of the Locals window is demonstrated with the following example.

1. In the VBE, double-click on Sheet1 (Sheet1) in the Project Explorer window.

2. Enter the code shown below into the editor window (you can copy and paste it into the window if you wish):

Sub ExploreRange()
Dim rg as Range
Set rg = Me.Range("A1")
Stop
rg.Value2 = 100
rg.Font.Bold = true
Stop
Set rg = nothing
End Sub

3. Place the cursor anywhere inside the procedure and press F5 to run it.

4. When code execution pauses at the first Stop statement, display the Locals window by selecting View\Locals Window.

5. Click on the + sign next to “rg” in the Locals window and take a minute to view all of the properties associated with the rg variable. In particular, observe the values for the Value2 property and the Bold property underneath the Font property.

6. Continue running the procedure by pressing F5.

7. At the second Stop statement, observe the Value2 and Bold properties.

8. Continue running the procedure by pressing F5.

You can even use the Locals window in conjunction with the Immediate window. For example, if you find a property in the Locals window that you want to change, you could enter a statement in the Immediate window to make the change. For example, in the proceeding example, you could enter

rg.Value2 = 250

in the Immediate window to change the value. The Locals window will reflect the change immediately. Note however that some properties are read-only.

That concludes my discussion of the various VBE windows. Now you’re ready to start coding! How about testing the water next week by discussing some ways to clean-up and optimize recorded macros?

Leave a Reply