Chapter 2

Getting Cozy with Visual Basic Editor

In This Chapter

arrow Understanding Visual Basic Editor components

arrow Working with the project window

arrow Using the code window

arrow Customizing Visual Basic Editor

Visual Basic Editor (VBE) is the environment where all Excel macros are stored and processed. Each workbook you create comes with this interconnected VBE environment free of charge. Even if you never record one macro, VBE is in the background waiting to be used. When you create a macro, VBE quietly comes to life ready to process the various procedures and routines you give it.

In this chapter, you take your first look behind the curtain to explore Visual Basic Editor.

Working in Visual Basic Editor

Visual Basic Editor is a separate application that runs when you open Excel. To see this hidden VBE environment, you’ll need to activate it. The quickest way to activate VBE is to press Alt+F11 when Excel is active. To return to Excel, press Alt+F11 again.

You can activate VBE also by using the Visual Basic command, which is on Excel’s Developer tab.

Understanding VBE components

Figure 2-1 shows the VBE program with some of the key parts identified. VBE contains several windows and is highly customizable, so chances are your window won’t look exactly like what you see in the figure. You can hide windows, rearrange windows, dock windows, and so on.

image

Figure 2-1: VBE with significant elements identified.

Menu bar

The VBE menu bar works just like every other menu bar you’ve encountered. It contains commands that you use to do things with the various components in VBE. Many menu commands have shortcut keys associated with them.

VBE also features shortcut menus. You can right-click almost anything in VBE and get a shortcut menu of common commands.

Toolbar

The standard toolbar, which is directly under the menu bar by default, is one of four VBE toolbars. You can customize the toolbars, move them around, display other toolbars, and so on. If you're so inclined, use the View  ⇒  Toolbars command to work with VBE toolbars. Most people just leave them as they are.

Project window

The project window displays a tree diagram that shows every workbook currently open in Excel (including add-ins and hidden workbooks). Double-click items to expand or contract them. You’ll explore this window in more detail in the “Working with the Project Window” section, later in the chapter.

If the project window is not visible, press Ctrl+R or choose View  ⇒  Project Explorer. To hide the project window, click the close button (the X) in its title bar. Alternatively, right-click anywhere in the project window and select Hide from the shortcut menu.

Code window

Every object in a project has an associated code window, which contains VBA code. To view an object’s code window, double-click the object in the project window. For example, to view the code window for the Sheet1 object, double-click Sheet1 in the project window. Unless you’ve added some VBA code, the code window will be empty.

You find out more about code windows later in the chapter in the “Working with a Code Window” section.

Immediate window

The immediate window may or may not be visible. If it isn’t visible, press Ctrl+G or choose View  ⇒  Immediate Window. To close the Immediate window, click the close button (the X) in its title bar (or right-click anywhere in the Immediate window and select Hide from the shortcut menu).

The Immediate window is most useful for executing VBA statements directly and for debugging your code. If you’re just starting out with VBA, this window won’t be that useful, so feel free to hide it and free up some screen space for other things.

Working with the Project Window

When you’re working in VBE, each open Excel workbook is a project. You can think of a project as a collection of objects arranged as an outline. You can expand a project by clicking the plus sign (+) at the left of the project’s name in the project window. Contract a project by clicking the minus sign (-) to the left of a project’s name. Or you can double-click the items to expand and contract them.

Figure 2-2 shows a project window with two projects: a workbook named Book1 and a workbook named Book2, expanded to display their objects.

image

Figure 2-2: This project window lists two projects.

Every project expands to show at least the Microsoft Excel Objects node. You can expand this node to display an item for each sheet in the workbook (each sheet is considered an object) and another object called ThisWorkbook (which represents the Workbook object). If the project has any VBA modules, the project listing also displays a Modules node.

Adding a new VBA module

When you record a macro, Excel automatically inserts a VBA module to hold the recorded code. The workbook that holds the module for the recorded macro depends on where you chose to store the recorded macro, just before you started recording.

In general, a VBA module can hold three types of code:

  • Declarations: One or more information statements that you provide to VBA. For example, you can declare the data type for variables you plan to use or set some other module-wide options.
  • Sub procedures: A set of programming instructions that performs some action. All recorded macros are Sub procedures.
  • Function procedures: A set of programming instructions that returns a single value (similar in concept to a worksheet function, such as Sum).

A single VBA module can store any number of Sub procedures, Function procedures, and declarations. How you organize a VBA module is up to you. Some people prefer to keep all their VBA code for an application in a single VBA module; others like to split up the code into several modules. It’s a personal choice, like arranging furniture.

Follow these steps to manually add a new VBA module to a project:

  1. In the project window, select the project’s name.
  2. Choose Insert  ⇒  Module.

Or you can

  1. Right-click the project’s name.
  2. Choose Insert  ⇒  Module from the shortcut menu.

The new module is added to a Modules folder in the project window (see Figure 2-3). Any modules you create in a given workbook are placed in this Modules folder.

image

Figure 2-3: Code modules are visible in the Modules folder in the project window.

Removing a VBA module

You may want to remove a code module that is no longer needed. To do so, follow these steps:

  1. In the project window, select the module’s name.
  2. Choose File  ⇒  Remove xxx, where xxx is the module name.

Or

  1. Right-click the module’s name.
  2. Choose Remove xxx from the shortcut menu.

remember You can remove VBA modules, but there is no way to remove the other code modules, those for Sheet objects or ThisWorkbook.

Working with a Code Window

As you become proficient with VBA, you'll spend lots of time working in code windows. Macros that you record are stored in a module, and you can type VBA code directly into a VBA module.

Minimizing and maximizing windows

Code windows are much like workbook windows in Excel. You can minimize, maximize, resize, hide, and rearrange them, and more. Most people maximize the code window that they’re working on so that they can see more code and reduce distractions.

To maximize a code window, click the maximize button in its title bar (right next to the X) or double-click the title bar. To restore a code window to its original size, click the restore button (the icon that looks like a box) located next to the X.

Sometimes, you may want to have two or more code windows visible. For example, you may want to compare the code in two modules or copy code from one module to another. You can arrange the windows manually, or use the Window  ⇒  Tile Horizontally or Window  ⇒  Tile Vertically command to arrange them automatically.

You can quickly switch among code windows by pressing Ctrl+Tab. If you repeat that key combination, you keep cycling through all open code windows. Pressing Ctrl+Shift+Tab cycles through the windows in reverse order.

Minimizing a code window gets it out of the way. You can also click the close button (the X) in a code window’s title bar to close the window completely. (Closing a window just hides it; you won't lose anything). To open it again, just double-click the appropriate object in the project window. Working with these code windows sounds more difficult than it really is.

Getting VBA code into a module

Before you can do anything meaningful, you must have some VBA code in the VBA module. You can get VBA code into a VBA module in three ways:

  • Use the Excel macro recorder to record your actions and convert them to VBA code.
  • Enter the code directly.
  • Copy the code from one module and paste it into another.

You have discovered the excellent method for creating code by using the Excel Macro recorder. However, not all tasks can be translated to VBA by recording a macro. You often have to enter your code directly into the module, either by typing the code by or copying and pasting code you've found elsewhere.

Entering and editing text in a VBA module works as you might expect. You can select, copy, cut, paste, and do other things to the text.

A single line of VBA code can be as long as you like. However, you may want to use the line-continuation character to break up lengthy lines of code. To continue a single line of code (also known as a statement) from one line to the next, end the first line with a space followed by an underscore (_). Then continue the statement on the next line. Here’s an example of a single statement split into three lines:

Selection.Sort Key1:=Range("A1"), _

Order1:=xlAscending, Header:=xlGuess, _

Orientation:=xlTopToBottom

This statement would perform the same way if it were entered in a single line (with no line-continuation characters).

VBE has multiple levels of undo and redo. If you deleted a statement that you shouldn’t have, use the Undo button on the toolbar (or press Ctrl+Z) until the statement appears again. After undoing, you can use the Redo button to perform the changes you’ve undone.

Ready to enter some real, live code? Try the following steps:

  1. Create a new workbook in Excel.
  2. Press Alt+F11 to activate VBE.
  3. Click the new workbook’s name in the project window.
  4. Choose Insert  ⇒  Module to insert a VBA module into the project.
  5. Type the following code into the module:

    Sub GuessName()

      Dim Msg as String

      Dim Ans As Long

      Msg = "Is your name " & Application.UserName & "?"

      Ans = MsgBox(Msg, vbYesNo)

      If Ans = vbNo Then MsgBox "Oh, never mind."

      If Ans = vbYes Then MsgBox "I must be clairvoyant!"

    End Sub

  6. Make sure the cursor is located anywhere within the text you typed, and then press F5 to execute the procedure.

tip F5 is a shortcut for the Run  ⇒  Run Sub/UserForm command.

When you enter the code listed in step 5, you might notice that VBE makes some adjustments to the text you enter. For example, after you type the Sub statement, VBE automatically inserts the End Sub statement. And if you omit the space before or after an equal sign, VBE inserts the space for you. Also, VBE changes the color and capitalization of some text. These changes are VBE’s way of keeping things neat and readable.

If you followed the previous steps, you just created a VBA Sub procedure, also known as a macro. When you press F5, Excel executes the code and follows the instructions. In other words, Excel evaluates each statement and does what you told it to do. You can execute this macro any number of times — although it tends to lose its appeal after a few dozen executions.

This simple macro uses the following concepts:

  • Defining a Sub procedure (the first line)
  • Declaring variables (the Dim statements)
  • Assigning values to variables (Msg and Ans)
  • Concatenating (joining) a string (using the & operator)
  • Using a built-in VBA function (MsgBox)
  • Using built-in VBA constants (vbYesNo, vbNo, and vbYes)
  • Using an If-Then construct (twice)
  • Ending a Sub procedure (the last line)

As mentioned, you can copy and paste code into a VBA module. For example, a Sub or Function procedure that you write for one project might also be useful in another project. Instead of wasting time reentering the code, you can activate the module and use the normal copy-and-paste procedures (Ctrl+C to copy and Ctrl+V to paste). After pasting the code into a VBA module, you can modify the code as necessary.

Customizing the VBA Environment

If you’re serious about becoming an Excel programmer, you’ll spend a lot of time with VBA modules on your screen. To help make things as comfortable as possible, VBE provides quite a few customization options.

When VBE is active, choose Tools  ⇒  Options. You’ll see a dialog box with four tabs: Editor, Editor Format, General, and Docking. Take a moment to explore some of the options found on each tab.

The Editor tab

Figure 2-4 shows the options accessed by clicking the Editor tab of the Options dialog box. Use the option in the Editor tab to control how certain things work in VBE.

image

Figure 2-4: The Editor tab in the Options dialog box.

The Auto Syntax Check option

The Auto Syntax Check setting determines whether VBE pops up a dialog box if it discovers a syntax error while you’re entering your VBA code. The dialog box tells roughly what the problem is. If you don’t choose this setting, VBE flags syntax errors by displaying them in a different color from the rest of the code, and you don’t have to deal with dialog boxes popping up on your screen.

The Require Variable Declaration option

If the Require Variable Declaration option is set, the VBE will insert an Option Explicit statement at the beginning of each new VBA module you add. When the Option Explicit statement appears in your module, you must explicitly define each variable you use. You get a detailed look at variables in Chapter 3.

The Auto List Members option

If the Auto List Members option is set, VBE provides some help when you’re entering your VBA code. It displays a list that would logically complete the statement you’re typing. This feature is one of the best in VBE.

The Auto Quick Info option

If the Auto Quick Info option is selected, VBE displays information about functions and their arguments as you type. This behavior is similar to the way Excel lists the arguments for a function as you start typing a new formula.

The Auto Data Tips option

If the Auto Data Tips option is set, VBE displays the value of the variable over which your cursor is placed when you’re debugging code. This option is turned on by default and is often quite useful. There is no reason to turn off this option.

The Auto Indent setting

The Auto Indent setting determines whether VBE automatically indents each new line of code the same as the preceding line. Most Excel developers are keen on using indentations in their code, so this option is typically kept on.

tip By the way, use the Tab key, not the spacebar, to indent your code. Also, you can press Shift+Tab to outdent a line of code. If you want to indent more than just one line, select all lines you want to indent and then press the Tab key.

VBE’s Edit toolbar (which is hidden by default) contains two useful buttons: Indent and Outdent. These buttons let you quickly indent or outdent a block of code. Select the code and click one of these buttons to change the block’s indenting.

The Drag-and-Drop Text Editing option

The Drag-and-Drop Text Editing option, when enabled, lets you copy and move text by dragging and dropping with your mouse.

The Default to Full Module View option

The Default to Full Module View option sets the default state for new modules. (It doesn’t affect existing modules.) If set, procedures in the code window appear as a single scrollable list. If this option is turned off, you can see only one procedure at a time.

The Procedure Separator option

When the Procedure Separator option is turned on, separator bars appear at the end of each procedure in a code window. Separator bars provide a nice visual line between procedures, making it easy to see where one piece of code ends and another starts.

The Editor Format tab

Figure 2-5 shows the Editor Format tab of the Options dialog box. With this tab, you can customize the way VBE looks.

image

Figure 2-5: Change VBE’s look with the Editor Format tab.

The Code Colors option

The Code Colors option lets you set the text color and background color displayed for various elements of VBA code. Most Excel developers stick with the default colors. But if you like to change things up, play around with these settings.

The Font option

The Font option lets you select the font used in your VBA modules. For best results, stick with a fixed-width font such as Courier New. In a fixed-width font, all characters are the same width. This type of font makes your code easier to read because the characters are nicely aligned vertically. You can also easily distinguish multiple spaces (which is sometimes useful).

The Size setting

The Size setting specifies the point size of the font in the VBA modules. This setting is a matter of personal preference determined by your video display resolution and how good your eyesight is.

The Margin Indicator Bar option

The Margin Indicator Bar option controls the display of the vertical margin indicator bar in your modules. You should keep this option turned on; otherwise, you won’t be able to see the helpful graphical indicators when you’re debugging your code.

The General tab

Figure 2-6 shows the options available on the General tab in the Options dialog box. In almost every case, the default settings are just fine.

image

Figure 2-6: The General tab of the Options dialog box.

The most important setting on the General tab is Error Trapping. If you are just starting your Excel macro-writing career, it’s best to leave Error Trapping set to Break on Unhandled Errors. This setting ensures that Excel can identify errors as you type your code.

The Docking tab

Figure 2-7 shows the Docking tab. Its options determine how the various windows in VBE behave. When a window is docked, it is fixed in place along one edge of the VBE program window. Docking makes it much easier to identify and locate a particular window. If you turn off all docking, you have a big, confusing mess of windows. Generally, the default settings work fine.

image

Figure 2-7: The Docking tab of the Options dialog box.

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

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