2.2. Using The Visual Basic Editor's Main Windows

In this section, you'll learn how to use the main windows of the Visual Basic Editor to get your work done.

2.2.1. The Project Explorer

The Project Explorer is the tool for navigating among the various objects in the Visual Basic Editor. Figure 2.3 shows the Project Explorer for a Visual Basic Editor session with Word as the host application.

Figure 2.3. use the Project Explorer to navigate to the module you want to work with.

Depending on the host application and its capabilities, each project can contain some or all of the following elements:

  • User forms (forms that make up part of the application's user interface, such as a custom dialog box).

  • Modules containing macros, procedures, and functions.

  • Class modules (modules that define objects, their properties, and their values).

  • References to other projects or to library files (such as DLLs — Dynamic Link Libraries).

  • Objects related to the application. For example, each Word document and template contains a Microsoft Word Objects folder that holds a class object named ThisDocument.ThisDocument gives you access to the properties and events (actions the object can react to, such as a click event) for the document or template. Each Excel workbook contains a class object named ThisWorkbook that gives you access to the properties and events for the workbook, and a Sheet object (named Sheet1, Sheet2, and so on) for each worksheet.

For most host applications, each open document and template is considered a project and is displayed as a root in the project tree. The project tree also contains any global macro storage container — such as the Normal.dotm template in Word, or the Personal Macro Workbook in Excel — and any add-ins that are loaded.

As an example, in Figure 2.3, Normal.dotm is identified as Normal, and the active document is identified as Project (2): a document named 2.

Change a Project's Name at Any Time

You can change the name of a project by using the Project Properties dialog box (discussed later in this chapter) or by selecting the project and entering a new name in the Properties pane directly below the Project Explorer pane. Once you change the name, the project is identified by that name in the Project Explorer, followed by the name of the document or template. For example, if you change the project name of the document 2 to Testing, the document project is identified as Testing(2) in the Project Explorer rather than Project(2).


You navigate the Project Explorer in the same way that you navigate the Windows Explorer folder tree: click the boxed plus sign to the left of a project item to expand the view and display the items contained in the project, and click the resulting boxed minus sign to collapse the view and hide the items again. Double-click a module to display its code in the Code window. Double-click a user form to display it in the Code window.

The Visual Basic Editor displays the Project Explorer by default, and because the Project Explorer provides fast and efficient navigation among the various elements of your VBA projects, it's usually easiest to keep it displayed unless you're short on screen space or you're working for long periods in the Code window and don't need to switch to other elements.

To close the Project Explorer, click its close button (the x button in its title bar). To display the Project Explorer again, press Ctrl+R or choose View Project Explorer. As you'll see later in this chapter, you can also undock the Project Explorer. This lets you push it aside when you need more room.

In Figure 2.3, three buttons appear on a toolbar at the top of the Project Explorer:

  • View Code Displays the Code window for the selected object. For example, if you select a user form in the Project Explorer and click the View Code button, the Visual Basic Editor displays a Code window containing any code attached to the user form. If you select a module or a class module in the Project Explorer and click the View Code button, the Visual Basic Editor displays a Code window containing the code in the module. You can also right-click an item in the Project Explorer and choose View Code from the shortcut menu.

    Double-Click Modules to View Their Code

    For a module or a class module, you can also double-click the object to view its code. This is usually faster than selecting it and then clicking the View Code button. For a user form or a file, however, double-clicking issues the View Object command (discussed next) rather than the View Code command.


  • View Object Displays a window containing the selected object. The View Object button remains dimmed and unavailable until you select an object (such as a user form or a file or object within a file) that can be displayed. If the selected object is a user form, clicking the View Object button displays the user form; if the selected object is a file or an object within a file, clicking the View Object button displays that object in the host application's window.

    For example, selecting the ThisDocument object for a Word document and clicking the View Object button displays the actual Word document in the Word window. Selecting the Sheet1 object in an Excel workbook and clicking the View Object button displays that worksheet in the Excel workbook in the Excel window.

    Viewing an Object

    You can also issue the View Object command by right-clicking an object and choosing View Object from the shortcut menu or by double-clicking an object that supports the View Object command. (If the object doesn't support the View Object command, double-clicking it issues the View Code command instead.)


  • Toggle Folders Toggles the view of the objects in the Project Explorer between folder view (a view that shows the objects grouped within their projects and folders) and contents view (which displays only the objects within their projects — no folders are shown).

    The left part of Figure 2.4 shows the Project Explorer for an application session sorted by folder view, and the right part shows the Project Explorer for the same situation in contents view. Whether you spend more time in folder view or contents view will depend on the size of your screen, the number of objects you put in any given project, and the way your mind works, not necessarily in that order. For many purposes, you'll want to toggle between folder view and contents view to locate objects most easily.

    Figure 2.4. Folder view (left) displays the objects separated into folders beneath the projects that contain them. Contents view (right) displays only the objects and the projects that contain them.

Apart from navigating to the items you need to work with, you can perform the following tasks with the Project Explorer:

  • Add or remove components from a project. For example, you can use the Project Explorer to add a module or a user form to a project.

  • Compare the components of one project to the components of another project. Such a comparison can be useful when you need to establish the differences between two or more projects quickly (for example, your reference copy of a company template and the copies users have been adding to).

  • Move or copy items from one project to another. You can drag a code module, class module, or user form from one project to another in the Project Explorer to copy it, or from the Project Explorer in one instance of the Visual Basic Editor to a project in the Project Explorer in another instance. For example, you could drag a user form from a Visual Basic Editor instance hosted by Excel to a Visual Basic Editor session hosted by PowerPoint to copy the user form. You can't, however, copy or move objects that are specific to a particular application's object model; you can't drop an Excel sheet into Word's Project Explorer because Word doesn't support that type of object.

  • Import or export a code module or a user form to or from a project.

The Project Explorer Is Your Best View

Many actions that you can perform through the Project Explorer you can also perform through the Visual Basic Editor's menu items, which is useful when the Project Explorer isn't displayed. In general, though, the Project Explorer provides the easiest way to navigate from module to module in the Visual Basic Editor, especially when you have several complex projects open at the same time. You can access the most commonly used commands for an object by right-clicking it in the Project Explorer to display the shortcut menu.


2.2.2. The Object Browser

The Visual Basic Editor provides a full Object Browser for working with objects in VBA. You'll look at the Object Browser in detail in Chapter 8, "Finding the Objects, Methods, and Properties You Need," and when you examine the object models for the various applications in the final part of the book. But, in the meantime, take a quick look at Figure 2.5, which shows the Object Browser for a Word VBA session. The Document object is selected in the left-hand panel, and its list of properties appears in the right-hand panel.

You'll find that a number of these properties immediately make sense from your knowledge of Word documents. For example, the AttachedTemplate property tells you which template the document is currently attached to. Likewise, the Bookmarks property contains information on all the bookmarks in the document. The property information is displayed at the bottom of the Object Browser.

2.2.3. The Code Window

You'll do most of the actual work of creating and editing your macros in the Visual Basic Editor's Code window. (Since code is written in plain text, you could simply write it in Notepad, then paste it into the code editor for testing and debugging. But the Visual Basic Editor offers so many useful programming tools that only the brilliant few can easily get good results by trying to wing it without any assistance from the editor.)

Figure 2.5. The Object Browser provides a quick way to look up objects and their properties. Here, you can see the properties contained in the Document object.

The Visual Basic Editor provides a Code window for each open project, for each document section within the project that can contain code, and for each code module and user form in the project. Each Code window is identified by the project name, the name of the module within the project, and the word Code in parentheses. Figure 2.6 shows the Visual Basic Editor Code window with the Transpose_Word_Right macro open in it.

Figure 2.6. You create and edit macros in the Code window.

As you can see from the figure, two dropdown list boxes appear just below the title bar of the Code window:

  • The Object dropdown list box at the upper-left corner of the Code window provides a quick way of navigating between different objects.

  • The Procedure dropdown list box at the upper-right corner of the Code window lets you move quickly from procedure to procedure within the current module. Click the down-arrow button to display the dropdown list of procedures. You'll see that the first procedure is (Declarations). This takes you to the Declarations area at the top of the current code sheet, which is where you declare public variables and other VBA information that multiple procedures need to know.

The Visual Basic Editor Code window provides a half-dozen features for helping you create code efficiently and accurately, as discussed in the following sections.

2.2.3.1. Complete Word

The Complete Word feature can complete the word you're typing into the code window, once you've typed enough letters to distinguish that word from any other. If you haven't typed enough letters to distinguish the word, the Visual Basic Editor gives you the closest possibilities (see Figure 2.7 ). You can either "type down" (continue typing to narrow the selection) or scroll through the displayed list to find the one you want.

Figure 2.7. The Complete Word feature automatically completes a term when you've typed enough to identify it. If you haven't typed enough, you can choose from a short list.

The easiest way to activate Complete Word when you're typing code is to press Ctrl+spacebar. You can also choose Edit Complete Word, or click the Complete Word button on the Edit toolbar (see Figure 2.8 ). Note that the Edit toolbar isn't visible by default. Open it by choosing View Toolbars Edit, or by right-clicking the toolbar area in the Editor, then choosing Edit from the shortcut menu that appears.

Figure 2.8. The Edit toolbar contains commands for working in the Code window.

2.2.3.2. Quick Info

The Quick Info command displays a ScreenTip showing syntax information about the currently selected variable, function, method, statement, or procedure. (Selected here just means the word in the code that's under or adjacent to the insertion point, the blinking cursor.) If you type in a command like MsgBox, then press the spacebar, the ScreenTip pops up to help you complete typing in the command. The tip shows both the required, and optional, elements of that command. Optional elements are enclosed in square brackets.

Figure 2.9 shows an example of a Quick Info ScreenTip.

Figure 2.9. Use the Quick Info command to get a quick reminder of syntax or a quick readout of status.

To issue the Quick Info command, use one of these methods:

  • Right-click the term and choose Quick Info from the shortcut menu.

  • Position the insertion point in the term and press Ctrl+I.

  • Position the insertion point in the term and choose Edit Quick Info.

  • If you're typing in actual commands from the VBA language (as opposed to, say, variables or objects), the easiest way to see Quick Info is just to type the command's name (such as MsgBox), then press the spacebar key.

2.2.3.3. List Properties/Methods

The List Properties/Methods command displays a pop-up list box containing properties and methods for the object you've just typed so that you can quickly complete the line of code. List Properties/Methods is switched on by default and automatically pops up the list box when you type a period in an object description, or a comma, parentheses, or other punctuation, in a line of code.

Alternatively, you can display the list box by clicking the List Properties/Methods button on the Edit toolbar.

To use List Properties/Methods, follow these steps:

  1. Press the down-arrow key to scroll down to the property or method, or scroll down with the mouse (see Figure 2.10). You can also type the first few letters of the property or method's name to jump to it.

    Figure 2.10. Use the List Properties/Methods command to enter code items quickly and accurately.
  2. Enter the property or method into the code:

    • Press Tab, or double-click the property or method, if you want to continue working on the same line after entering the property or method.

    • Press Enter if you want to start a new line after entering the property or method.

2.2.3.4. List Constants

The List Constants command displays a pop-up list box containing constants for a property you've typed so that you can quickly complete the expression. List Constants is switched on by default. Alternatively, you can display the list box by clicking the List Constants button on the Edit toolbar.

To use List Constants (see Figure 2.11), follow these steps:

  1. Press ↓ to scroll down to the constant, type its first letter (or first few letters), or scroll down with the mouse.

  2. Enter the constant in the code:

    • Press Tab, or double-click the constant, if you want to continue working on the same line after entering the constant.

    • Press Enter if you want to start a new line after entering the constant.

Figure 2.11. The List Constants feature saves you time and effort, especially when typing complex constant names.

2.2.3.5. Data Tips

The Data Tips feature displays a ScreenTip containing the value of a variable the mouse pointer moves over when the Visual Basic Editor is in Break mode (a mode you use for testing and debugging macros). Figure 2.12 shows an example. The Data Tips feature is switched on by default, but you can switch it, and other features, off by choosing Tools Options.

Figure 2.12. Use the Data Tips feature to check the value of a variable when you're running code.

2.2.3.6. Margin Indicators

The Margin Indicators feature lets you quickly set a breakpoint, the next statement, or a bookmark by clicking in the margin of the Code window. You'll look at setting breakpoints, setting the next statement, and setting bookmarks later in this book. (You can just right-click the gray margin on the left side of the code window, then choose Toggle from the shortcut menu to manipulate breakpoints or bookmarks. Or just left-click to toggle breakpoints.)

2.2.3.7. Other Editing Features

Apart from these features, the Code window includes standard Office editing features such as copy and move, cut and paste, and drag and drop. Drag and drop is particularly useful, because you can drag code from one procedure or module to another.

2.2.4. The Properties Window

The Visual Basic Editor provides a Properties window you can use to view and modify the properties of an object in VBA, such as a project, a module or class module, a user form, or a control (a button or check box in a dialog box, for example). The dropdown list at the top of the Properties window lets you pick the object whose properties you want to view or modify. The Alphabetic option displays an alphabetical list of the properties in the item, and the Categorized option presents a list of the properties broken down into categories. Generally, I find the categorization less than useful because many properties don't really fit neatly into any particular category.

Figure 2.13 shows the Alphabetic option with the properties for an Excel workbook on the left, and the Categorized page on the right. (Showing the Categorized page for the Excel workbook or worksheet isn't very helpful, as all of the properties belong to a Misc. category — miscellaneous.)

Figure 2.13. Use the Properties window to view the properties of a project, a user form, module, class module, or a control.

Many of the workbook properties are easy to grasp. For example, the HasRoutingSlip property is set to False, indicating that the workbook does not have an e-mail routing slip attached to it; and the Saved property is set to True, indicating that the workbook does not contain any unsaved changes. You'll meet the properties for user forms in Chapters 14 and 15, but for now, look at properties such as Caption (which is listed in the Appearance category and sets the text in the user form's title bar) and Height (which appears in the Position category and specifies the height of the user form in points).

Understanding Design Mode, Run Mode, and Break Mode

The Visual Basic Editor uses three modes, reflecting three fundamental phases of programming — writing, locating a bug, and fixing a bug:

Design mode Also known as design time. Any time you're working in the Visual Basic Editor on your code, you're in Design mode. You don't have to be actively designing anything visually — such as a user control or form — although you often will be. You will also often just be typing in source code — the commands that Visual Basic will execute when you switch to Run mode.

Run mode Also known as runtime. When code is running, you're in Run mode. The macro will be executed just as if it had been launched from within an application like Word (using a shortcut key combination, or via clicking on a Quick Access Toolbar button). The purpose of Run mode in the Visual Basic Editor is to allow you to observe the code's behavior and interact with it if necessary, to see that it works as it's supposed to. This is known as debugging. If you do find any problem during runtime testing, you can stop the execution by pressing Ctl+Break, and then check the values in variables, or otherwise attempt to track down where in your code the error is located. VBA itself can also throw you into Break mode if it detects an error condition.

Break mode When code is running but execution is temporarily suspended, you're in Break mode. Break mode lets you step through your code one command or one procedure at a time (rather than running all the commands at once at full speed). Stepping is a very handy tool when you're debugging or otherwise critiquing your code. You'll explore debugging techniques in detail in Chapter 17.


The Visual Basic Editor displays the Properties window by default, but you can close it by clicking its close button (the x button). To display the Properties window again, press F4 or choose View Properties Window.

To change a property, click the cell containing the property name. If a down-arrow button appears in the value cell, click it to choose a new value from a dropdown list. If no button appears, click the value cell to display the blinking insertion cursor and type in a new value.

You'll be able to choose different values from dropdown lists, depending on the type of property: For a True/False property, you'll be limited to those two choices in the drop-down list; for a text property such as Name, you can enter any valid VBA name.

By default, the Properties window is docked below the Project Explorer. You can resize the Properties window or the Project Explorer by dragging the border between them, or you can resize both at once by dragging the border to their right. If you undock the Properties window, you can resize it by dragging its borders or corners to display more properties or to shrink the window so it takes up less space in the Visual Basic Editor. Undock interior windows (also called panes, such as the Properties window) by dragging it by its title bar, or by double-clicking its title bar; redock by double-clicking its title bar.

2.2.5. The Immediate Window

Beyond the Project Explorer, the Code window, and the Properties window, the Visual Basic Editor includes a number of other windows that it doesn't display by default. Two of the key windows are the Object Browser (which you met earlier in this chapter) and the Immediate window, which you'll use during the discussion of the VBA language in Chapter 5.

The Immediate window, shown in Figure 2.14, is a small, unadorned window you can use as a virtual scratch pad to enter lines of code you want to test without entering them in an actual macro itself. When you type a line of code into the Immediate window and press the Enter key, the Visual Basic Editor executes that code.

Figure 2.14. Use the Immediate window for on-the-fly work and information.

To display the Immediate window, press Ctrl+G or choose View Immediate Window. To close the Immediate window, click its close button. Ctrl+G or choosing View Immediate Window are not toggles, so if you perform those actions a second time, you will not close the Immediate window.

Display Variables' Status During Debugging

You can also use the Immediate window to display information to help you check the values of variables and expressions while code is executing. That is done by using the Debug.Print command, like this example, which displays the value of the variable x in the Immediate window:

Sub ShowDebug()

Dim x As Integer
x = 12

Debug.Print x

End Sub


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.161.49