Programming Publisher 2003 Made Easy: Lesson 1

 

Andrew May
Microsoft Corporation

October 2004

Applies to:
    Microsoft Office Publisher 2003

Summary: Learn how easy it is to use the Publisher object model to write macros that automate tasks in Publisher and save you time and effort. This lesson discusses what a macro is and how to write one in Publisher 2003. (9 printed pages)

Contents

Introduction
Getting Started
Writing Your First Macro
Using Sub Procedures
Review
Conclusion
Additional Resources

Introduction

Do you have things that you do repeatedly in Publisher? Do you find yourself doing a certain set of tasks over and over again? Wouldn't it be great if you could tell Publisher to perform complicated tasks automatically? Guess what? You can. There's a way to give Publisher detailed instructions on what you want it to do to, when you want it to do it, and even under what conditions, and have Publisher carry out all your instructions automatically.

You can do this by writing a macro. What's a macro? Simply put, a macro is a set of instructions that tell a program like Publisher to do something, written in a way that the computer program can understand.

This is the first in a series of lessons to teach you how to use the Publisher object model to write macros that make your life easier and ease your Publisher woes. Each self-contained lesson introduces core programming concepts, with plenty of examples and hands-on exercises to show you what we're talking about. You don't need any special experience, just a computer with Publisher installed. After each lesson you'll have learned skills you can start using in your macros right away.

Getting Started

Writing macros can be easy. Take a look at the following example. You can probably figure out what this macro does just by looking at it:

Sub SetFirstRowHeight()
  Dim pubPage As Page
  Dim pubShape As shape
  For Each pubPage In ActiveDocument.Pages
    For Each pubShape In pubPage.Shapes
      If pubShape.Type = pbTable Then
        pubShape.Table.Rows(1).Height = "0.4 in"
      End If
    Next pubShape
  Next pubPage
End Sub

This macro formats the height of the first row in each table in the active publication. For each page in the publication, the macro looks at each shape. If the shape is a table, it sets the height of the table's first row to 0.4 inches. Then it examines the next shape, and so on, for all the shapes on the page. Then it repeats the same process for the next page, and the next, through-out the rest of the publication.

If you have a large document with lots of tables, or many documents to format this way, you can see pretty quickly how much time and effort these few lines of code could save you.

Although writing a basic macro is simple, macros can be as complex and flexible as you need, and represent a powerful way to customize Publisher to do whatever tasks you want it to do at the click of a button. Those instructions can be quite involved, with details like user input and conditional branching and lots of other stuff you don't need to consider right now.

For a more complex example, let's assume your business maintains a Web site, with a catalog of the products you sell. Every few weeks, you use the catalog merge functionality in Publisher to recreate the catalog, with new products added and discontinued items deleted, and then repost the Web site using the Web publishing features in Publisher. The whole process takes several hours you could easily spend doing something else. So you create a macro that performs the whole update and republish automatically. . .

No Experience Necessary

The best part is, it's easy. You don't need a degree in computer science, or any specialized technical background. All you need is a little knowledge and some examples to get you thinking. And that's where the lessons in this series come in.

Over the course of the lessons in this series, we'll walk you step-by-step through how to create and run macros in Publisher. No experience or special knowledge necessary. Each lesson contains examples and hands-on exercises that illustrate the programming concepts discussed. Because of this, it's probably best if you work through the lessons in front of your computer.

All you need to work through the lessons is a computer with Publisher 2003 installed. That's it. You should be able to finish each lesson in under an hour. While each lesson builds on the ones before it, each is self-contained, so after each lesson you'll have learned skills you can start using in your macros right away. And you can stop after any lesson and walk away with practical skills. But we're betting that, once you realize how easy and useful programming is, you won't want to.

What You'll Learn

By the time you're finished with the lessons, you'll have a working knowledge of the fundamentals of the Microsoft Visual Basic programming language. In addition, you'll have experience using the Publisher 2003 object model, and have learned how to use it to create solutions for your business needs.

Let's get right to it. Here's what you'll learn in this lesson:

  • How macros can save you time and energy by automating tasks in Publisher
  • How to write and run a basic macro
  • How to access and use the Visual Basic Editor that comes as part of Publisher

So let's get started.

Writing Your First Macro

Now that we told you what a macro is, and the kind of things you can do with one, let's get a little deeper into how you actually write them. You write macros using Microsoft Visual Basic for Applications (VBA). VBA is a version of the Microsoft Visual Basic computer language which is integrated into Microsoft Office applications, such as Publisher. When you write macros in VBA, you are creating instructions that use the Publisher 2003 object model. The Publisher object model is a collection of the objects you can use to customize Publisher; we'll discuss it in more detail later.

Now let's look at where you'll be writing your Publisher macros.

To write a macro in Publisher

  1. Open Publisher 2003. Under New in the Task Pane, click New Blank Publication.

    Note   You can actually open any Publisher file and write macros. For now, to keep it simple, we'll just use a new blank publication.

  2. From the Tools menu, select Macro, and then click Macros.

  3. For Macro Name, type MyFirstMacro and click Create.

    Tip   A macro name can't contain spaces. So, while MyFirstMacro is okay, My First Macro would not work.

Publisher starts what looks like another program. Each Office application that is VBA-enabled, like Publisher, includes a separate but linked program that lets you write and edit VBA. It's called (imaginatively enough), the Visual Basic Editor (VBE).

**Tip   **You can also get directly to the VBE from the Tools menu, by selecting Macro, and then clicking Visual Basic Editor. However, if you do so, the Code window may not display by default, so let's open the VBE this way for now.

Figure 1. The Visual Basic Editor

By default, the Visual Basic Editor displays three windows.

  • **Code window   **The window labeled "Publication1 – [Module1(Code)]". This is where you write your macro code.
  • **Project Explorer window   **The window labeled "Project – Project". This window shows objects and modules included in this project. Don't worry if that doesn't mean anything to you yet. We discuss that later. This window allows you to view and manage the VBA files in this project.
  • **Properties window   **The window labeled "Properties – Module1". This window displays the current properties for whatever item you've got selected.

Tip   If you ever accidentally close one of these windows or one of them doesn't appear, you can re-open it from the View menu.

Now let's use each one of these windows.

You use the Properties window to view and edit the current properties of the selected item. So let's change the name of Module1. In the Properties window, on the Alphabetic tab, double-click the text "Module1" and type "Lesson1". Notice that the name changed in the Project window and in the title bar of the Code window.

The Project window enables you to navigate the objects and files in your VBA project. Click the plus sign next to the Microsoft Office Publisher Objects folder, to expand that node. Notice that the ThisDocument object resides in that folder. We'll be using that object in future lessons.

Finally, let's complete the MyFirstMacro we started. Look at the code window: notice that Publisher inserted the following code for us:

Sub MyFirstMacro()
 
End Sub

Looks nice, doesn't it? Unfortunately, it doesn't do anything. The Sub and End Sub statements are just the wrapper for the macro. We need to add the code that actually tells Publisher what to do. Type (or copy and paste) the following lines between the two statements, so the finished macro looks like this:

Sub MyFirstMacro()
  Dim pbShape As Shape
  
  Set pbShape = ActiveDocument.Pages(1).Shapes.AddTextbox(1, 100, 100, 100, 100)
  pbShape.TextFrame.TextRange.Text = "Hello World"
End Sub

You don't need to know how or why the code works right now. That'll come in later lessons. Right now, let's put this macro to work.

To run the macro in Publisher

  1. Return to Publisher. On your Windows task bar, click the Publisher button.

    Save the Publisher file. This also saves the macro.

  2. From the Tools menu, select Macro, and then click Macros.

  3. MyFirstMacro should already be selected, as it's the only macro available. Click Run.

Did Publisher add a new text box with the text "Hello World" to the upper right-hand corner of the first page in your publication? If so, congratulations! You've now joined the ranks of Publisher programmers.

If you got an error message, or nothing happened, no big deal. If you got an error, click the button to get ride of the error message. Now go back to the VBE Code window and make sure what you typed looks exactly like the code above, and then try running the macro again.

If nothing happened, your security settings might be the reason. So let's take a minute to talk about that.

Adjusting Security Settings to Enable Macros

Publisher lets you set the macro security level that determines which macros can run on your computer. If the Publisher macro security level is Very High or High, only macros that Publisher can verify came from trusted sources can run. All other macros are automatically disabled and do not run. This even applies to macros you yourself create. By default, the macro security level for Publisher 2003 is High. So unless you already changed it, chances are the macros you write may not even run on your own computer.

To change the macro security setting in Publisher

  1. From the Tools menu, select Macro, and then click Security.

  2. On the Security Level tab, click Medium, and then click OK.

    **Important   **You should also never set your macro security settings to Low. If you do so, you are not protected from potentially unsafe macros.

  3. Close Publisher and restart. Make sure to save your publication before you close it. The change in security setting doesn't take effect until you restart Publisher.

Don't worry about losing your macro code. Publisher saves it in the publication you opened when you were writing it. So just make sure to save your publication before you close Publisher. Then just re-open Publisher, and re-open the VBE.

Now that you have your macro security at Medium, Publisher examines each publication before it opens it to determine if it contains macro code. If it does, Publisher alerts you and asks if you want to enable those macros:

Figure 2. Macro Security Alert Dialog Box

This allows you to choose to enable macros you trust, such as the ones you write, and disable macros you're not sure about.

**Important    **You should never enable macros from a source you aren't familiar with, or are uncertain about.

Using Sub Procedures

Macros are also called sub procedures, or more commonly, just procedures. A procedure is a set of code statements that tell Publisher, or really any application, to do something.

Right now you only have a single procedure in your code module, MyFirstMacro. But you can have any number of procedures in a module. How does Publisher tell them apart, or tell where one ends and another begins?

Simple. All procedures adhere to the same pattern:

Sub MacroName()
   Code statements
End Sub

Use the key words Sub and End Sub to begin and end a procedure. The first line identifies the procedure, and tells Publisher where to start running the code. The last line, the End Sub statement, tells Publisher that it's reached the last line of the macro and to stop.

**Tip   **Key words are words that have special meaning in Visual Basic. For example, Sub and End Sub are key words that tell Visual Basic where the start and end points of a procedure are.

Calling Procedures from Other Procedures

You don't have to run procedures directly, as you do when you select a macro from the Macros dialog box and click the Run button. You can also run, or call, one procedure from within another procedure. All you have to do is include the name of the procedure in a code statement in the other procedure. Try it. In the Code window of the Visual Basic Editor, add the following procedure:

Sub MySecondMacro()
  ActiveDocument.Pages.Add 1, 0
  MyFirstMacro
End Sub

Now run the MySecondMacro procedure. The first line of code adds a blank page to the publication (don't worry about how for now). The second statement calls the MyFirstMacro procedure, which adds a text box.

What's the advantage of this, instead of just putting all your code in one long procedure? Creating separate procedures enables you to organize your code more logically, and cuts down on code duplication. For example, suppose you have a task you want to perform as part of three different macros. You can make that task a separate procedure, and just call it from within the three macros. That way, you only have to write the code for the task once. And if you need to change the code later, you only have to maintain it in one place.

Saving Your Procedures

To save your procedures, simply save the Publisher file from which you opened the Visual Basic Editor. The procedures you write are saved as part of the Publisher file itself. If you save the file and exit Publisher, the VBE closes as well. To get back to your procedures, just open the file in Publisher, and then open the VBE as well.

**Note   **To run a macro, you have to be in the Publisher file that contains the macro. You can't run the macro from another Publisher file, whether or not the file containing the macro is open. For example, open the file we've been working in. From the Tools menu, select Macro, and then click Macros. The MyFirstMacro procedure should be listed. Now, open a new file and view the macros available in it. The list should be empty, because the new file contains no macros.

Review

Here's a quick recap of what we covered in this lesson:

  • Macros are a great way to save time and effort by automating repetitive tasks. A macro is a set of instructions that tell a program like Publisher to do something, written in a way that the computer program can understand.

  • You use the Visual Basic Editor to write your macros. You can open the VBE from within Publisher from the Tools menu, by selecting Macro, and then clicking Visual Basic Editor.

  • The Visual Basic Editor opens with three windows showing by default: the Project, Properties, and Code windows. The Code window is where you write your macro code.

  • Be sure to adjust the macro security setting in Publisher to enable the macros you write to run.

  • Macros are also called procedures. All procedures adhere to the following pattern:

    Sub MacroName()
       Code statements
    End Sub
    
  • You can run, or call, procedures from within other procedures.

Conclusion

Now that wasn't too painful, was it? You're now officially a Publisher object model programmer. In Lesson 2, we examine the code we're writing a little more closely and find out how it actually does what it does. We'll also introduce the simple concept that underlies the most powerful aspects of macro programming: object-oriented programming.

See you there.

Acknowledgments

Special thanks go out to Frank Rice, for allowing me to steal the structure of his Super-Easy Guide to the Microsoft Office Excel 2003 Object Model article for this series of lessons. Thank you, Frank.

Additional Resources

This section lists a number of resources you can use to learn more about the products and technologies mentioned or used in this article.

Sites:

Publisher Home on MSDN

Articles:

Programming Publisher 2003 Made Easy: Lesson 2

Programming Publisher 2003 Made Easy: Lesson 3

Programming Publisher 2003 Made Easy: Lesson 4

Programming Publisher 2003 Made Easy: Lesson 5

Blogs:

Andrew May