This documentation is archived and is not being maintained.

Programming Publisher 2003 Made Easy: Lesson 2

Office 2003
 

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 energy. This lesson reviews the core concepts of object-oriented programming: how to use object, properties, methods, and events in your procedures. (11 printed pages)

Contents

Introduction
Anatomy of an Object
Exercise
Using Events
Review
Conclusion
Additional Resources

Introduction

In our last lesson, we introduced the macro, a set of instructions you can write to have an application like Publisher perform complex tasks for you at the push of a button. Then we showed how easy it is to write one.

In this lesson, we build on that by introducing you to object-oriented programming. Don't be put off if that sounds intimidating. Truth is, if you completed the last lesson, you're already an object-oriented programmer.

We'll talk about the three simple concepts you need to understand object-oriented programming, look at a few examples, and then jump in and see how it works first-hand.

Anatomy of an Object

So what is an object, anyway? In programming, an object is just a model of a real-world thing. Objects can have properties and methods. To understand object-oriented programming, you really only need to keep three very simple concepts in mind:

  • Object A model of a real-world thing.
  • Property A property is a characteristic of an object.
  • Method A method is something an object can do.
Note   In addition, objects also have events. An event is something that happens that an object can react to. But we'll discuss events in depth later in this lesson.

You can categorize everyday things into objects, methods, and properties. For example, consider a car to be an object. A Car object has methods or various things it can do, such as Start, Drive, and Turn. A Car also has properties that describe it: the color is red and the number of headlights is two.

If it helps, you can think of objects as nouns, properties as adjectives that describe the noun, and methods as verbs, that is, actions the noun takes. For example:

"The red (property) car (object) turned (method) left at the corner."

The Publisher 2003 object model is just a list of the objects available to you for writing procedures. In general, objects in the Publisher's object model tend to fall into two broad categories: either things you find in a Publisher file, or things you find in the Publisher user interface. For example, consider the following list of objects:

Table 1. Some of the Objects in Publisher 2003

Things in a Publisher (.pub) file: Things in the Publisher user interface:
Page ScratchArea
BorderArt PageSetup
Hyperlink Window
DropCap RulerGuide
HeaderFooter AdvancedPrintOptions
Shape WebPageOptions

Unusual capitalization aside, you probably recognize the real-world items these objects represent. The ScratchArea, RulerGuide, and Window objects represent things in the Publisher interface: the scratch area around the boundaries of the publication, the ruler guides that measure the publication, and the Publisher window itself. The PageSetup, AdvancedPrintOptions, and WebPageOptions objects all represent Publisher dialog boxes.

When you want to use a property or method of an object, type the object name, a period, and then the property or method name, like so:

ObjectName.PropertyName

Let's look again at the macro we wrote in the last lesson, and see what objects, properties and methods we can identify:

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

This macro contains one method, AddTextbox. This method belongs to the Shapes object, and as you probably guessed, the method adds a text box shape to the shapes on the page. To use a method or property of an object, just place a period between the object and the method. In this case, that's Shapes.AddTextbox.

The procedure also contains a single property, Text, which belongs to the TextRange object. It's a property, so it's a characteristic of an object. In this case, the characteristic is the TextRange object's text.

One last thing to know: Every object is a specific type of object. Each type of object has its own set of methods, properties, and events. For example, an object of type Car would have very different methods, properties, and events from an object of type House.

Or we can use examples from the Publisher object model. The Publisher object model contains a Page object. Page objects have methods, such as Duplicate or Move, and properties, such as Height, that other types of objects may not have. In addition, other types of objects may have methods or properties which the Page object does not have. For example, the following statement:

Page.Value = "Hello"

Does not work because objects of type Page do not have a property called Value.

Finding the Methods and Properties of an Object

So how, you might ask, do I find out what properties and methods an object has? Here's one way. When you type in the name of an object in your code, and then type a period, the Visual Basic Editor displays a list of the properties and methods belonging to that object. You can then select the property or method you want, and press the Tab key to insert it into your code.

Tip   Methods are the ones with the green eraser icon, while properties have the icon of a hand holding an index card.

Figure 1. The VBE Displaying the Methods and Properties of the Shape Object

Pop Quiz 1

Look at the following fictitious example and determine which parts are objects, properties, and methods. Hint: there are three of each.

Set PetStore = ShoppingMall.GetStore(aPetStore)
PetStore.OpeningTime = 9 AM
Set Dog = PetStore.GetPet(aDog)
Dog.Breed = "Cocker Spaniel"
Dog.Color = "Blond"
Dog.WagTail

Look for the answer at the end of this lesson.

Using Your Objects

To use an object in your procedures, it's often useful to create a variable to contain the object first. Objects take up space in computer memory. You can think of a variable as a cubbyhole in computer memory, into which you can place objects.

You give the cubbyhole a name, so that when you refer to it in your code, you actually refer to the object it contains.

To Create and Use an Object Variable

  1. Declare the variable name, and define what type of objects you want to store in it. You do this by using a declaration statement, using the following pattern:
    Dim variableName As objectType
    
    

    The Dim keyword just means you're creating a variable. For objectType, you specified the type of object you want the variable to contain, such as Page, or Shape, objects.

    Dim myDocument as Document
    
    
  2. Set the contents of the object variable. To do this, use the Set keyword, and then specify the object you want stored in your variable, like so:
    Set myDocument = ActiveDocument
    
    

    This code sets your variable to contain the third shape on the first page of the active publication.

  3. Refer to the object variable name whenever you want to use that object in your procedure.

    Now whenever you use the object variable in your procedure, you actually use the object you stored in it. For example, you can change the properties of the object using the following lines of code:

    myShape.TextFrame.TextRange.Text = "Watch This Space."
    myShape.Fill.ForeColor.RGB = 255
    myShape.Hyperlink.Address = "http:\\www.microsoft.com"
    
    

    And so on.

Just remember, it's called a variable because you can vary its contents. In other words, you can store different objects in it at different times. To change the contents of an object variable, just use the Set keyword again to specify the new contents of the variable. For example, you can take the myShape object variable and store different shapes in it at different times.

But you can't store an object in an object variable if the object is of a different type than the variable. For instance, you can't squeeze a Page object into an object variables made to contain Shape objects, or vice versa.

Pop Quiz 2

Take a look at the following code:

Set myShape = ActiveDocument.Pages(1).Shapes(3)
myShape.Fill.ForeColor.RGB = 255
Set myShape = ActiveDocument.Pages(2).Shapes(1)
myShape.Fill.ForeColor.RGB = 0

This code sets the myShape object variable to two different shapes: the third shape on the first page, and the first shape on the second page. If 255 is bright red, and 0 is black, what colors are each shape?

Look for the answer at the end of this lesson.

Exercise

So let's apply our new-found knowledge to a practical, real-world scenario.

Suppose you're a small business owner, and every few weeks you create a newsletter to mail to your customers. The format of the newsletter is always the same: the design is "Banded Newsletter," the color scheme is "Cavern," there's a calendar on page three and a sign up form on page four. How about we create a macro that does all that for you automatically?

To create the CreateNewsletter macro:

  1. Open Publisher, and open or create the publication in which you want to create the macro.
  2. From the Tools menu, select Macro, and then click Visual Basic Editor.

    If the Code window is not displayed, from the View menu, select Code.

  3. In the Code window, type the following code:
    Sub CreateNewsletter()
      Dim newDoc As Document
      
      Set newDoc = Application.NewDocument(pbWizardNewsletters, 52)
      newDoc.ColorScheme = newDoc.Application.ColorSchemes("Cavern")
      newDoc.Pages.AddWizardPage 2, pbWizardPageTypeNewsletterCalendar
      newDoc.Pages.AddWizardPage 3, pbWizardPageTypeNewsletterSignupForm
      
    End Sub
    
    
  4. Save the publication.
  5. Run the macro.

And there you have it. The macro creates a newsletter, sets its color scheme to "Cavern," and then adds two new pages. The one with a calendar is inserted after page two, and the page with the sign up form is inserted after page three.

Making Your Methods Do More

As you typed in the code, you might have noticed the Visual Basic Editor displaying tips and drop-down menus. Most of these were probably for the properties and methods of objects, like we discussed earlier. However, a few probably happened when you were typing in the names of methods. For example, when you typed in the NewDocument method, you probably saw something that looked like this:

Figure 2. The VBE Displaying what parameters the method has, and your choices for the first parameter

That's because the NewDocument method has parameters. Parameters give you choices for what you want the method to do. For example, the NewDocument method has two parameters:

  • The first parameter lets you select the wizard template you want to base the new publication on. In our case, that's the newsletter wizard, named pbWizardNewsletters.
  • The second parameter lets you select the design you want for the publication. We chose design number 52.

See how that lets you get even more flexible in your procedures? You can select exactly the type and design of your new publication, just by setting the two method parameters. In most cases, the VBE displays what parameters a method has, and presents you with the choices available for each parameter as you move through them.

When a method has more than one parameter, you separate the parameters with a comma.

Tip   If the VBE displays a parameter in brackets ([ ]), that means the parameter is optional. You don't have to use it if you don't want to. Both the parameters of the NewDocument method are optional.

Using Events

So now you have a macro that creates a newsletter publication for you. But you still have to run the macro. What if you could run the macro automatically, every time you opened the publication you saved the macro in? Then, whenever you wanted to create a new newsletter, you just open the publication you saved the macro in. Well, it turns out you can do just that.

Because in addition to properties and methods, objects can have events. An event is something that happens to an object that it can respond to. The table below lists some things you can do to a publication. In the next column, it lists the events belonging to the Document object.

Table 2. Things You Can Do to a Document, and Corresponding Document Object Events

Things You Can Do to a Document Document Object Events
Open the document. Open
Add shapes to the document. ShapesAdded
Delete shapes from the document. ShapesRemoved
Close the document. BeforeClose

If you want an object to do something when one of its events occurs, you write a special kind of procedure called an event handler. It's only a little different from a macro procedure. Here's the basic pattern for this type of procedure:

Private Sub ObjectType_Event
   Code statements
End Sub

Let's write an event handler that automatically runs the CreateNewsletter macro every time you open the publication that contains that macro.

To Create An Event Handler Procedure

  1. Open the publication you saved the CreateNewsletter macro in, and open the Visual Basic Editor.
  2. In the Project Explorer window, click the expand icon next to Microsoft Office Publisher Objects. You should see the ThisDocument object listed. The ThisDocument object is an object that represents the Publisher publication in which you are working.

    Figure 3. The Project Explorer window.

  3. Double-click the ThisDocument object. This opens a Code window titled "[ThisDocument (Code)]".
  4. In the Code window, notice the two pull-down menus across the top of the window. In the left-hand menu, select Document. The right-hand menu then displays the events of the ThisDocument object. Select Open from the right-hand menu.

    Figure 4. The "ThisDocument" Code window.

    Notice that the Visual Basic Editor creates an empty Document_Open event handler procedure for you:

    Private Sub Document_Open()
    
    End Sub
    
    
  5. To call the CreateNewsletter procedure, just type its name in the Document_Open event handler procedure.
    Private Sub Document_Open()
      CreateNewsletter
    End Sub
    
    

Save the publication and close it. When you re-open the publication, your macro should run automatically.

Do It Yourself Challenge

Write a macro that displays a dialog box every time you add a shape to the publication. Here's the code that displays the dialog box:

MsgBox "You added a shape."

Look for the answer at the end of this lesson.

Review

An object is a model of a real-world thing. Objects have properties, methods, and events. A property is a characteristic of an object. A method is something an object can do. An event is something that happens that an object can react to.

In general, objects in the Publisher's object model tend to fall into two broad categories: either things you find in a Publisher file, or things you find in the Publisher user interface.

To find out the properties and methods of an object, in the Code window, type the object name, followed by a period. The Visual Basic Editor displays a list of the properties and methods belonging to that object.

To use an object in your procedures, it's often useful to create a variable to contain the object. You can think of a variable as a cubbyhole in computer memory, into which you can place objects. To create an object variable:

  1. Declare the variable name, and define what type of objects you want to store in it:
    Dim variableName As objectType
    
    
  2. Set the contents of the object variable, using the Set keyword:
    Set myShape = ActiveDocument.Page(1).Shapes(3)
    
    
  3. Use the object variable name to refer to that object.

Some methods have parameters, which give you choices for what you want the method to do. When a method has more than one parameter, you separate the parameters with a comma.

Objects can also have events, which are something that happens to an object that it can respond to. If you want an object to do something when one of its events occur, you write a special kind of procedure called an event handler. Here's the basic pattern for this type of procedure:

Private Sub ObjectType_Event
   Code statements
End Sub

Answers

Answer: Pop Quiz 1

Look at the following fictitious example and determine which parts are objects, properties, and methods. There are three of each.

Set PetStore = ShoppingMall.GetStore(aPetStore)
PetStore.OpeningTime = 9 AM
Set Dog = PetStore.GetPet(aDog)
Dog.Breed = "Cocker Spaniel"
Dog.Colore = "Blond"
Dog.WagTail

Table 3. Answers to Pop Quiz 1

Objects Methods Properties
ShoppingMall GetStore OpeningTime
PetStore GetPet Color
Dog WagTail Breed

Answer: Pop Quiz 2

Here's the code again:

Set myShape = ActiveDocument.Pages(1).Shapes(3)
myShape.Fill.ForeColor.RGB = 255
Set myShape = ActiveDocument.Pages(2).Shapes(1)
myShape.Fill.ForeColor.RGB = 0

The third shape on page one is bright red, and the first shape on page two is black.

The first Set statement sets the myShape variable to contain the page one shape. The next line of code turns its forecolor RGB value to 255, or bright red. Next, the second Set statement sets the myShape variable to contain the page two shape, so any code that refers to the myShape variable now refers to the page two shape, not the page one shape. So the final line of code, myShape.Fill.ForeColor.RGB = 0, turns the page two shape's fore color to black.

Answer: Do It Yourself Challenge

Here's how you would write a macro that displays a dialog box every time you add a shape to the publication. First, make sure you're in the ThisDocument code window. If you're not, double-click the ThisDocument icon in the Project Explorer window. Next, select Document from the left-hand drop-down menu, and the ShapesAdded even from the right-hand drop-down menu. When you do, the Visual Basic Editor automatically creates an empty Document_ShapesAdded procedure for you. Now add the line of code we gave you, so that the finished event handler procedure looks like this:

Private Sub Document_ShapesAdded()
  MsgBox "You added a shape."
End Sub

Save the publication. Now, whenever you add a shape to the publication, Publisher should display the following dialog box:

Figure 5. Dialog Box

We'll talk more about creating dialog boxes in our next lesson.

Conclusion

In this lesson we introduced the basic concepts of object-oriented programming, and showed how to use them to produce useful macros. Now that you've mastered these simple concepts, you've got the building blocks you need to create flexible, powerful macros to automate and customize Publisher.

In our next lesson, we'll talk about how to create custom dialog boxes to communicate with the user of your macros. We'll also introduce programming logic you can use to make your macros even more flexible and useful.

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 1

Programming Publisher 2003 Made Easy: Lesson 3

Programming Publisher 2003 Made Easy: Lesson 4

Programming Publisher 2003 Made Easy: Lesson 5

Blogs:

Andrew May

Show: