Introduction to the VBA Language and Code Structure

The easiest way to begin learning VBA is to record macros and then look at what you’ve recorded in the Visual Basic Editor. In the subsections that follow, we’ll use this method to help you become acquainted with how to read VBA code.

Note

Macros can no longer be recorded in PowerPoint (which has always been the most limited of the three programs in terms of VBA capabilities), but you can still write VBA macros in PowerPoint. Macros can be recorded and written in Word and Excel.

So, what is a macro? A macro is simply a set of commands that can be executed together, similar to a paragraph style. However, where a style is a collection of settings that you can apply at once, a macro is a collection of actions.

Recording Macros

When you record a macro, literally every step you take is recorded, including moving your insertion point up or down or making a selection. Note that, while recording a macro, your insertion point can’t be used as a selection tool. Use the arrows on your keyboard, along with the Shift key, to make selections as needed while recording a macro.

Note

Experienced users of VBA continue to find macro recording useful for learning how to accomplish new tasks in VBA. One thing we all run into at some point, however, is the fact that a handful of commands can’t be recorded. For example, if you record a macro while adding items to the Quick Access Toolbar or the Quick Styles gallery, your steps won’t be recorded. In some cases, a macro that can’t be recorded means that you can’t accomplish the task through VBA, but it doesn’t always. You can do a great many things when writing VBA that can’t be done by recording macros, such as applying a document Theme. Learn more about this later in this chapter, as well as how to get help for finding commands that can’t be recorded.

To begin recording a macro, on the Developer tab, in the Code group, click Record Macro. Or, on the status bar, click the Record Macro icon shown beside this paragraph.

Note

Once you click Record Macro, the icon changes to a blue Stop Recording box. Click Stop Recording on either the Developer tab or the status bar when you’ve finished recording your macro.

Let’s try one together, as an example. Say that you’re starting a new, long presentation document. Each page of the document needs to begin with Headings 1, 2, and 3, consecutively, followed by a paragraph of body text. The first several pages of that document will each begin with the text Company Overview—in the Heading 1 paragraph, which will be followed after the em dash by different text on each page.

To save a bit of time, let’s record a macro for setting up these pages.

With your insertion point at the top of the empty document, click Record Macro and then do the following.

  1. In the Record Macro dialog box, type a name for your new macro. Macro names must start with a letter and can include letters, numbers, and the underscore character, but can’t include spaces or most special characters.

    Notice in the Record Macro dialog box, shown here, that recorded macros are stored, by default, in the global template Normal.dotm.

    Setting Up the Sample Document

    In the Save In drop-down list, you have the option to select any open document or template, including currently loaded global document templates (Building Block and Quick Style Set templates won’t be available here). For now, leave the default Save In setting and click OK to begin recording.

  2. Apply Heading 1 style to the active paragraph.

  3. Type Company Overview—(To add the em dash, you can use the keyboard shortcut Ctrl+Alt+(keypad)-.)

  4. Press Enter four times.

    Because Style For Following Paragraph has been set for the first three heading styles, these four hard returns add paragraphs with the styles Heading 2, Heading 3, and Body Text, consecutively, followed by an additional Body Text paragraph. That additional Body Text paragraph is where your insertion point will be when the macro starts to run again, so it will become Heading 1 style in the first step of the macro.

  5. Click Stop Recording.

To run that macro, on the Developer tab, click Macros, select the macro you just recorded, and then click Run.

With this particular macro, you could run it each time you need to set up a page, or run it as many times as you’ll need identical pages. Or, you could edit it to add functionality that enables it to do even more for you, such as automatically adding the number of pages you need. But, for the moment, let’s just look at this macro as an example to demonstrate how to read VBA code.

How to Read VBA Code

To view the macro you just recorded, on the Developer tab, click Macros. Then, select your macro from the Macro Name list and click Edit. This will open the Visual Basic Editor with your macro open on screen. Your screen should look something like the following image.

How to Read VBA Code

For now, focus on the macro itself—we’ll look at the different elements of the Visual Basic Editor shortly.

  • Sub stands for subroutine, which is basically just another term for macro. Every macro begins with Sub and ends with End Sub, as you see in the preceding example.

  • The first few lines below Sub in the preceding example have an apostrophe at the beginning of the line. Those are comments. An apostrophe at the beginning of a line of VBA code means that there is no code to run on that line. When you record macros, VBA automatically adds some comment lines, one of which includes the name of the macro, as you see in the preceding image.

    You can delete any line that begins with an apostrophe without damaging the macro. Be sure, however, not to delete the apostrophe and leave other text on the line that you don’t want to run as a VBA command. The apostrophe is what causes the line to be skipped when the macro runs.

  • After the comment text, you see the commands that comprise the steps of this macro. If you tried this for yourself and you see more lines of code in your macro than in my sample, ask yourself if you took other steps. If, for example, you made a typo in the Company Overview text and went back to correct it, that could have been recorded as a collection of several steps. Remember that when a macro is recorded, every keystroke is recorded. So, each time you use a different arrow key to move your insertion point, for example, you’ll get another line of code. Take a look again at the commands from the preceding macro.

    Selection.Style = ActiveDocument.Styles("Heading 1")
    Selection.TypeText Text:="Company Overview—"
    Selection.TypeParagraph
    Selection.TypeParagraph
    Selection.TypeParagraph
    Selection.TypeParagraph

Notice that this code doesn’t include any unfamiliar terms, even if you’ve never seen a line of VBA code before. Selection, style, active document, type text, and type paragraph all refer to extremely basic Word tasks. The majority of program-specific terms in VBA will be similarly familiar, just from your experience with the program.

As you progress through this primer, you’ll come to understand how to construct the lines of code you see above and how you can write your own macros that are even simpler than recorded macros for accomplishing the same tasks.

Statements, Procedures, Modules, and Projects

To begin to work in the Visual Basic Editor, one of the most important things to understand is how files work in VBA—that is, how macros are organized and stored. The following common items are the principal components you need to know.

  • A statement is a single command or action in a macro—that is, it’s a line of code. For example, Selection.Font.Bold = wdToggle is a statement. As you’ll see in "Writing, Editing, and Sharing Simple Macros", when you think of VBA as a language, think of a statement as a sentence.

  • A procedure is, essentially, another way of referring to a macro, although there are other types of procedures as well, such as functions. A function is a procedure that returns a result.

  • A module is a collection of code. Think of a module as a code document. A module can contain several procedures. And, like documents, modules can be saved as files, copied, and shared.

  • A project is the collection of all modules and related VBA objects in your document, template, or add-in. A project might have one or several modules, as well as other elements such as UserForms (dialog boxes).

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

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