Example: Adding a Closing to a Letter

Perhaps the best way to get a feel for creating and using UserForm objects is to go through some examples, which I suggest that you follow along with on your PC. In this example, we create an application that inserts an ending in a Word letter. There are three types of endings: friendly, formal, and hostile. We want the user to be able to select between these three alternatives and click a command button to automatically insert the ending. We also want the user to be able to type in a name in a text box. This name will be used in the ending as well. (In this way, more than one user can use the application.)

Add a UserForm Object and Set Its Properties

The first step is to choose the project in which to place the UserForm object. The most logical choice would be a template that is used for writing letters, or, if no such template exists, then the project for the Normal template, making the form available to all documents.

Once you’ve chosen the template in which your code will reside, switch to the VBA Editor, select the desired project, and use the Insert menu to add a UserForm to the project. Once the form is visible (as in Figure 20-1), we can make use of the Properties window to make the changes shown in Table 20-1 to its properties.

Table 20-1. Nondefault UserForm Properties

Property

Value

Name

frmLetterEnding

Caption

Letter Ending

StartUpPosition

CenterScreen

Add Controls to the Form

The next step is to place a few controls on the form. ...

Get Writing Word Macros, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.