Working with pictures and graphics in Microsoft Word is easy when you know what to do. Use the tips in this helpful editing guide and watch the tutorial video below to see just how easy it is.
Insert a Picture or Logo
- On the Insert menu, click on Picture, and then click From File.
- Browse to locate the picture you want to insert.
- Double-click the picture you want to insert.
Move a Picture or Graphic Anywhere on a Page
You may notice that you can’t move an inserted picture or graphic freely around on the page. This is an easy fix:
- Click on the Picture Tools tab.
- Under Arrange, select Text Wrapping.
- Choose In Front of Text.
Now, you can freely move the graphic around the page and move it to the desired location.
Move a Picture or Graphic Forward or Backward
If your photo or clip art is overlapping other graphics and text, you may want to move it forward or backward.
- Select the image.
- In the Picture Tools tab select Send to Back.
- Use these tools to move graphics forward and backward one position at a time, or all the way to the front or back.
Resize or Crop a Picture
When an image is too big for the space, or not the right shape, you’ll want to crop or scale it. Remember not to distort the image by sizing it up or adjusting from the edges. Scale the graphic down by clicking on a corner and moving your mouse inward towards the center of the image. If you just want to reduce the size on one or more sides, select the crop tool and use the handlebars to make the appropriate adjustment.
- Click the picture or shape you want to resize.
- Drag a sizing handle away from or toward the center.
- Select the picture that you want to crop.
- Under Picture Tools, on the Format tab, in the Size group, click Crop.
- Drag the cropping handles on that side or corner you want to adjust.
Note: Vector artwork can be scaled without loss of picture quality.
Make a Picture into a Shape
If you have the need, you can make your photo a circle or other shape.
- On the Insert tab, click on Shapes.
- Draw your shape on the page.
- Under the Drawing Tools tab, click Fill Shape and choose Picture.
- Navigate to the photo you would like to insert into your shape.
- Under the Drawing Tools tab, change the shape outline to no outline.
Edit the Color of a Shape or Clip Art
You can easily change the color of vector graphics or clip art in your layout.
- Select the graphic.
- Go to the Drawing Tools tab.
- Click on Shape Fill and select a color.
Don’t you wish you could open your own letterhead or marketing documents in Word just like it was a pre-designed layout from Microsoft’s free template library? You can! A document saved as a Microsoft Word Template creates a copy of the original with each new use. This makes creating new projects convenient and you’ll never overwrite your original document. In the example below, I will show you how to save a StockLayouts flyer layout as a Word Template for future use.
1. Open or create your marketing piece.
2. Edit the design to your company’s specifications.
3. Click the Microsoft Office Button, and then click Save As > Word Template.
4. In the Save As dialog box, do one of the following:
On a computer that is running Windows Vista, under Favorite Links, click Templates.
On a computer that is running Windows XP, under Save in, click Trusted Templates.
5. Give the new template a file name, select Word Template in the Save as type list, and then click Save.
When you are ready to start a new project with this design:
- Click the Microsoft Office Button, and then click New.
- In the New Document dialog box click New from Existing under Templates.
- Navigate to your design and click Create new.
For more details about saving Microsoft Word Templates visit the Microsoft help guide.
Graphic Design Resources
View business marketing templates from StockLayouts.
View MS Word document templates from LayoutReady.com.
Learn more about customizing templates with Graphic Design Tutorial Videos.
Try our free design templates to see how easy they are to customize.
You may want your letterhead graphics to display on each page of your letterhead, report, or other document. When you continue to type on to a new page, Word will simply create a blank page. To repeat the graphics on the background of each new page, follow the steps below.
Watch this helpful video for tips on working with graphics in Microsoft Word.
1. Open a template or create your letterhead layout.
2. Edit the letterhead to your company’s specifications.
3. Cut and paste the letterhead graphics into the header.
- Select all of the graphics.
- Right click on the graphics and navigate to Grouping > Group.
- Right click on the graphics and select Cut.
- On the Insert tab, select Header.
- Insert a Blank header.
- Paste the graphics into the document.
- Click Close Header and Footer.
The graphics will appear grayed out.
Your letterhead will now repeat on the background of any new pages added to the document.
Graphic Design Resources
View ready-made letterhead design templates from StockLayouts.
Get a quick start with Microsoft Word letterhead templates from LayoutReady.
Try a free letterhead template download and see how easy templates are to customize.
The first part of this tutorial A Pop-up Calendar for Word Part 1: A Simple Calendar showed you how to build a very basic calendar tool. This tool works well but, because it is simple, it is also limited in function. The date format is "hard-coded" into the calendar and can't be changed by the user unless they have a knowledge of VBA.
This tutorial improves on the basic calendar by allowing the user to choose a date format from a number of pre-defined options, and to specify their own custom format if they wish. It allows a chosen format to be set as the default by storing the calendar settings in the Windows Registry.
Here are the main features of the improved pop-up calendar tool:
- As with the Simple Calendar, this tool can be called up using a keyboard shortcut or from an option on the right-click context menu.
- The current date is displayed by default. The user can browse for a date using the calendar.
- The user can choose the format in which the date will be entered into their document. Any date format can be set as the default.
- A custom date format can be specified and saved as the default to save time next time.
- The form displays a sample of the date in the chosen date format.
- Once set up the tool can be used to enter dates into a document quickly and easily. To enter today's date in the chosen saved format you just have to press CTRL+SHIFT+C, ENTER (or whatever keyboard shortcut that you have specified followed by ENTER).
About Date Formats
VBA uses the standard method of defining date formats that you are probably familiar with from other programs such as Microsoft Excel. If you are not familiar with the codes used, follow this link to see an explanation and some examples (the link displays the help text that will be included later in this project).
Building the Calendar Form
The first part of this tutorial explained the basics of building a VBA UserForm and showed how to locate and insert the ActiveX Calendar Control. This tutorial assumes that you have mastered the (simple!) skills of form building and will concentrate on the VBA code necessary to make everything work.
To make sure that you have all the objects necessary, and that they all have the same names as I use when referring to them in the code, build your form to look like the one illustrated below (you are free to design your calendar any way you like, but make sure that you modify your code to suit):
A Note About Using Frames on UserForms
You can see that I have used frames to divide the UserForm into sections and arrange the controls into visual groups. This is a cosmetic feature and does not affect the performance of the form. When using frames like this it is usually easier to place a frame on the form before placing the objects that will appear inside the frame. Then, if you move the frame the objects inside it will move too and retain their correct positions in relation to it.
Set the Properties of the Controls
As you add the various objects (controls) to the form apply the settings shown in the table below to their properties. To do this, first select the control then find the appropriate property in the Properties Window (normally in the lower left corner of the Visual Basic Editor). If the Properties Window is not visible, switch it on from the View menu. Set the Name property of each control according to the illustration above, then set the following:
|Frame1||Caption||Select a date:|
|Frame3||Caption||Select a date format:|
|Frame4||Caption||Custom date format:|
|lblSample||Caption||Monday 01 January 2001|
|Set as default |
Now the form is complete, and it's time to start writing the VBA code to power it.
What the Code Has to Do
In the first part of this tutorial, the code for the basic calendar didn't have to do very much. When the user chose a date the code had to write the date, in a predefined format, into the current document then close the calendar form.
In this tutorial the code has a lot more to do because it is offering much more functionality:
- It must convert the user's selections into an acceptable date format.
- It must display a sample of the date in the specified format.
- It must be able to store and retrieve the user's preferences.
- It must write the date, in the user's specified format, into the current document and close the calendar form.
In addition, I have added help for the user in the form of an additional UserForm displaying information about date formats.
Download the Code
I believe that if you type out the code yourself it will help you learn the VBA, but there's quite a lot of code here so you might prefer to copy the whole lot and paste it into the form's code module. Follow this link to open a window containing the entire code module for the calendar form.
To get the code, click the link above to open the web page. Click anywhere on the page and press CTRL+A to select all the text, then CTRL+C to copy it. Switch to your Visual Basic Editor and click on the calendar form to select it. Press F7 (or go toView > Code) to open the form's code module then press CTRL+V to paste the code into the module. To make sure everything got copied properly, go to Debug > Compile Project. The compiler will highlight any problems.
I hope you are here because you want to learn about VBA! So read through the next section to find out what each piece of code does and why it needs to do it...
Writing the VBA Code
This section explains what all the various bits of code do, why they are necessary, and will help explain the logic behind my VBA code writing.
A Function to Create a VBA Date Format
Near the top of my code is a function that I have called DateFormat. I wrote the function because its code is used many times by different procedures. Placing the code into a function like this makes re-using it much easier and saves a great deal of typing! The purpose of this function is to turn the choices that the user has made from the various check boxes and option buttons into a usable VBA date format. Each section of the date (dayname, daynumber, month and year) are analysed with an If Statement and an appropriate code defined. Here is the one used for the months:
Note that an appropriate separator is defined depending on the user's choice. I have only done this for the month If Statement because (in UK English) it is most common to use a slash (/) or a space to separate the parts of a date. If the month is written as a number the date parts are normally separated by slashes (e.g. 27/9/2003 or 27/09/2003) but if it is written as text they are normally separated by spaces (e.g. 27 Sep 2003 or 27 September 2003). The separators are not normally used the other way (e.g. 27 09 2003 or 27/Sep/2003).
NOTE: If you live, work or are building your calendar for use in a country that uses a different date-writing convention you can change the separator definitions to suit your requirements. But you can't always anticipate the user's needs, so if you can't decide what to do, remember that this calendar tool also allows the user to define and save their own custom date format.
After all the choices have been analysed they are assembled into a single date format code:
NOTE: I have used the European convention of writing dates in the order day-month-year. If you use a different method (e.g. US month-day-year) you can rearrange the code accordingly (e.g. for US swap the positions of strMonth and strDayNumber).
Here is the complete code for the function [click the thumbnail to see a full-sized image]:
Check Boxes and Option Buttons
According to the conventions form design, check boxes and option buttons do different things. If you are used to building forms in Access you will find that they work in a different way there than in a VBA UserForm.
|I placed my option buttons and check boxes inside a frame. This has no effect on how they work (unlike Access forms). On a VBA UserForm option buttons can work as a group but they don't do so automatically (unlike Access forms). When they work as a group, the act of selecting one member of the group deselects the others. If you want option buttons to work as a group, you must define the group by assigning the same value to the GroupName property of each member of the group.|
Check boxes are different. They can't work as a group (unlike Access forms) even though they have a GroupName property (programmers make use of this property for other purposes).
I have arranged my option buttons in logical groups. The user has only two choices of how a year is displayed so there are two option buttons in the Year group. There are four ways a month can be displayed so there are four option buttons in the Monthgroup. But although there are four ways to display a day (short or long number, short or long name) the user might want to choose one or two of the options, so a single group won't do.
I have included the first two option buttons (short and long number) in the group DayNumber. I wanted the other two choices to look different so I put them on the form as check boxes, but in order to make them work as a group - so that when one was selected the other was deselected - I needed to write some code. Something else had to be taken into consideration. You can deselect a selected check box by clicking it (click once to add the tick, click again to remove it). My code had to work in such a way as not to interfere with this.
Coding the Check Boxes
I wanted the two DayName check boxes to act as a group, as if they were grouped option buttons. If one is already chosen and the user and the user clicks the other, then the choice moves to the one they just clicked (i.e. the tick is removed from the other). But I still need to retain the characteristic behaviour of check boxes, that a selected check box can be deselected with a click. The following code is attached to the AfterUpdate event of each check box (with the check box names changed accordingly):
The If Statement looks at the updated state of the check box and, if it is True (i.e. contains a tick), it sets the value of the other check box to False (i.e. no tick). This makes sure that the situation can not arise in which both check boxes contain a tick, but does allow a situation where both do not contain a tick.
There is also a line which writes a caption into the lblSample label (below the calendar) so that it displays an updated example of the date format to include the change that the user has just made. Note that this uses the DateFormat function described above.
Coding the Option Buttons
The option buttons don't really need to do anything. Another procedure (the DateFormat function) reads their values so that a format code can be assembled. But, as with the check boxes, each time the user makes a selection that change needs to be reflected in the example date displayed by the lblSample caption. Each option button has exactly the same line of code attached to its AfterUpdate event. Here's an example:
The Custom Date Format Tool
This tool allows the user to devise a date format of their own design using the standard date formatting codes. The tool consists of a check box and a text box working together. To enter a custom code the user types directly into the text box. As they type their changes generate an example date displayed by the lblSample caption:
[Point at the image above to play the animation]
This is achieved by code running on the Change event of the txtCustom text box. Whenever the contents of the text box change this code examines the value of the text box:
If the text box contains some text the code sets the value of the chkCustom check box to True and generates an example date for display in lblSample using the contents of the text box for the format code. As the animation above shows, this sample is generated and modified as the user types each letter of their format code so they can see exactly how their typing builds the date.
If the text box becomes empty (i.e. its value is "") the code sets the value of the chkCustom check box to False and has the lblSample caption display an example date using the current settings in the "Select a date" section.
Because these changes cause the value of the chkCustom check box to change, this causes additional changes to take place on the form. I decided that simply allowing the user to type a custom format into the text box wasn't enough. I wanted it to be clear to the user that they were either applying a custom format or not. For this reason, when the chkCustom check box is ticked the txtCustom text box is enabled but all the formatting option buttons and check boxes in the "Select a date format" section are disabled. If the chkCustom check box is not ticked those option buttons and check boxes are enabled, and the txtCustom text box is disabled.
These changes are made by the following procedure running on the Change event of the chkCustom check box:
To simplify the procedure, and reduce the amount of typing involved I created a custom function containing the long list of commands to either enable or disable all the date format check boxes and option buttons. The function, which I called EnableControls, accepts True or False depending on whether the controls are to be enabled or disabled. See the beginning of the full code listing for the function code.
Disabling the txtCustom text box does not remove its contents. This is because the user might choose to set a custom date format as their default date format, but not necessarily want to use it every time. Allowing it to remain in place saves them from having to type a commonly used formatting code every time they want to use it. In the illustration below, the custom code is greyed out because (as determined by the check box) custom formatting is not currently enabled.
Setting a Default Date Format
The whole point of a pop-up calendar is that it makes entering a date quick and easy. People are most likely to write their dates the same way each time. If the they have to specify the format every time, the process becomes less convenient. To solve that problem I have added a "Set as Default" tool.
There are various ways to save user preferences. I have two preferred methods: saving the information in a text file, and saving the information in the Windows Registry. Both are easy to achieve using VBA. For this project I have chosen to use the Registry. Here's how it works...
The principle is very simple. When the user has defined a date format they click the "Set as Default" command button. The procedure records the value of each check box, and option button as well as the custom date format check box and text box. Each value is written to the Registry. Here's the code that does it:
The procedure loops through all the controls on the form. The If Statement checks the control's type and if it is a CheckBox, OptionButton or TextBox it records the control's name and value in the Registry. When you use the Registry from VBA like this you don't need to get involved with editing the Registry yourself, the code does it all for you (but please read my note on Working with the Registry below). In case you're interested, the Registry entry will look something like this:
In the procedure shown above this is what the various bits of code mean:
SaveSetting - This VBA method means "record the following information in the Registry" and it has the following four arguments...
AppName - Essentially a category (in fact a folder) in which the information will be stored. I have called mine "Fontstuff" - you can call it anything you like. If the AppName folder does not already exist the procedure creates it.
Section - A sub-folder within the AppName category. I have called it "WordPopupCalendar". It makes sense to give it a meaningful name. If the Section folder does not already exist the procedure creates it.
Key - This is an object within the section folder which can store a value. The code procedure creates a key (if one does not already exist) for each of the controls on the form (as defined by the If Statement) and gives the key the same name as the control.
Setting - This is the value stored by the key. The code procedure assigns the value of the control to the key with the same name.
The illustrations below show a complete set of date format settings on the form and the resulting Registry entries [click the thumbnail to see a full-sized image]:
Folders created by the VBA SaveSetting method are always located in the same place in the Windows Registry:
My Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings\
Applying the Default Settings with the Initialize Event
When a VBA UserForm opens its Initialize event happens. I have used the UserForm_Initialize event procedure to set up the form and to retrieve any default settings from the Registry. Here's the entire procedure [click the thumbnail to see a full-sized image]:
First, the code checks the user's selection (in case they selected some text before they called up the calendar) and if can be read as a date, it sets the calendar to match that date. If it doesn't recognise the selection as a date, or if no text is selected, it sets the calendar to the current date. It then enables the form's OK button:
Next it uses the GetSetting method to check the Registry for any default settings:
The VBA GetSetting method is used to retrieve values from the Registry. In the same way as before, when the value of each control was stored in the Registry using the SaveSetting method, the values have to be read one-at-a-time.
First of all the If Statement tries to read the value of one of the controls (I have chosen to use chkddd but any one would do). If no value can be found for that control a value of "" is returned. This means that there can be no default settings in the Registry, so the first part of the If Statement makes a number of settings itself (I have chosen m/d/yy). If, on the other hand, a value is returned by the initial GetSetting enquiry, the second part of the If Statement loops through the form's controls using GetSetting to retrieve the value of each one from the registry, and applies that value to the control.
Finally, because of the order in which the code loops through the controls (option buttons, then check boxes and finally the text box), if there is a value for the txtCustom text box the process of entering the value sets the chkCustom check box to True - even though its stored value may be False! This is annoying... but these things happen in VBA. So, there is an additional line that retrieves the value of the chkCustom checkbox again to make sure it is correct.
The last line of the procedure writes a caption for lblSample to match the calendar's date and the format settings:
Coding the Calendar Control's Events
In the first part of this tutorial, the calendar code had only one function to perform. When the user chose a date, that date was entered into the document and the calendar closed automatically. Their choice triggered the control's Click event and the date-writing code was located in the Calendar1_Click procedure.
The requirements are slightly different here. We do not need the calendar to do anything other than "remember" the user's choice. The date will not be written to the document until they click the form's OK button. But we do require any change of date to be reflected in the lblSample example. Here's the revised Calendar1_Click procedure:
Notice that the last line of the Calendar1_Click procedure enables the form's OK button. This is because there are two event procedures which will disable it: the NewMonth and the NewYear event.
You might expect that, when you change the calendar's month or year by choosing one from the drop-down lists at the top of the calendar control, the dame day number would remain selected. But is doesn't - the result is that no day number is selected (don't ask me - they just programmed it that way!). In the simple calendar that didn't matter because the act of choosing a day fired the calendar's Click event which wrote the date into the document. Here that isn't the case, so we have to make sure that the user doesn't click the form's OK button until they have chosen a complete date (i.e. they have chosen a day number).
Fortunately there are NewMonth and NewYear events that fire when the user chooses a new month or a new year and these can be used to disable the OK button. As mentioned above, the OK button is enabled again when the user chooses a day number, causing the Calendar1_Click event to fire.
Coding the Command Buttons
Having chosen a date and a suitable format, the user can insert the date into their document by clicking the OK button (cmdOK); they can close the calendar without entering a date by clicking the Cancel button (cmdCancel); or they can ask for more information by clicking the Help button (cmdHelp).
The Default property of the cmdOK button has been set to True so that if the user presses the Enter key on their keyboard it has the effect of clicking the OK button. Similarly, the Cancel property of the cmdCancel button has been set to True so that if the user presses the Escape key on their keyboard it has the effect of clicking the Cancel button.
The Cancel Button
The Click event of the Cancel button is used to close the form without making any changes to the document:
The OK Button
The Click event of the OK button writes the chosen date to the document, but first it uses an If Statement to look at the state of the chkCustom check box. If the check box is ticked it formats the date with the custom format; if not it formats the date using the settings in the "Select a date format" area. Having written the date into the document it moves the user's cursor to the end of the date entry and closes the form:
The Help Button
You can choose to omit the Help button if you want, but I think it is useful so have included one. Usually, clicking a button marked Help invokes the Windows Help system. Compiling custom help is not a simple matter and a small project like this doesn't really justify the effort. so instead I have supplied help in the form of another UserForm (see below). The UserForm is called frmHelp and the Click event of the Help button simply displays this form:
Building the Help Form
The Help Form (frmHelp) is very simple, containing a frame (Frame1) inside which is a label (Label1) displaying the help text. There is a command button (cmdExit) to close the form.
Build the form to look like the illustration above and set the Name property of each control according to the illustration above, then set the following:
|Frame1||ScrollBars||2 - fmScrollBarsVertical|
|ScrollHeight||550 (see note below)|
Draw the frame first then draw the label inside it. When entering a lot of text into a label like this, you will probably find it easier to type directly on to the label rather than into the Caption property box. To make a new line in your text pressSHIFT+ENTER.
The frame's scrollbar does not automatically scroll far enough to display all the text so you have to adjust the ScrollHeight property of the frame to make it fit.
If you do not want to make up your own help text you can follow this link to copy the text used in this example.
The Help Form needs only two small pieces of code. The UserForm_Initialize procedure sets the ScrollTop property of the frame to zero, ensuring that it opens displaying the beginning of the help text:
The cmdExit_Click procedure closes the form when the Exit button is clicked:
Because the Cancel property of the cmdExit button was set to true the form will also close if the user presses the Escape key on their keyboard.
Coding the Word Document
Opening the Calendar
All the code which follows can be placed into the document's ThisDocument code module. For the user to be able to make use of the calendar tool, it is essential to include a macro to display the calendar on demand:
You can leave it at that if you want, and the user can open the calendar by running the OpenCalendar macro from the menu in the normal way (Tools > Macro > Macros...) but since the whole point of this project is to make work easier for the user it makes sense to make opening the calendar a simple as possible...
Adding A Keyboard Shortcut and a Menu Item
The following procedure defines a keyboard shortcut for running the macro (and thus opening the calendar), and creates a new entry on context menu that appears when the user right-clicks on the page:
The first part of this procedure assigns the keyboard shortcut CTRL+SHIFT+C. You can choose your own keyboard shortcut by changing the keycode constants specified. For a list of suitable keycodes ask VBA Help about the BuildKeyCode method and follow the link to WdKey.
The second part of the procedure creates the new menu item "Insert Date". Again, you can change text of the menu item (the caption) but make sure that the OnAction property refers correctly to the name of the macro that opens the calendar.
Before the instruction to create the menu item I have included a line of code to delete the same menu item! The reason for this is that in some circumstances, for example if the document closes incorrectly because Word has crashed, the menu item might not be removed as it should be. This line makes sure that the menu item is not duplicated. The inclusion of the statement On Error Resume Next tells the program to ignore the error that would otherwise occur if the code tries to delete a menu item that isn't there.
NOTE: I have assumed that the document that is being created here will be saved as a Word Template and installed as an Add-In (instructions for doing this follow below). In this case the above code is contained in the Document_Open procedure. If you are going to include the code in a regular template (i.e. you will not install it as an Add-in) you should put the above code in the Document_New procedure.
Removing the Keyboard Shortcut and Menu Item
When the template closes, the keyboard shortcut should be cancelled and the menu item removed. This is achieved by the following short code procedure:
Save the Calendar Template
What you do with the word document now depends upon when you want the calendar to be available. If you want the calendar to be available to all your documents whenever you use Word, then the document should be saved as a Word Template (*.dot) file.
Go to File > Save As, give the file a suitable name (mine is called WordPopupCalendar) and change the Save as type: setting to Document Template (*.dot).
To install the template as a Word Add-in it must be located in Word's Startup folder. For instructions on how to do this, refer to the section "Installing the Calendar" in the first part of this tutorial. The procedure is exactly the same.
You may prefer not to install the template as a Word Add-In and instead use it as a regular template. If you use the template like this, the calendar will only be available to documents based on that template, and not all your Word documents.
The next step is to add the VBA code that will power the form. Five different code procedures (sometimes called Macros) need to be written. First, a procedure to "initialize" the form when it opens; a procedure to respond to the clicking of each of the three command buttons; and a procedure to open the form automatically when the document is opened.
Initializing the Form
In the Visual Basic Editor open the form's code window by selecting the form and pressing the F7 key. Alternatively right-click the form's name in the Project Explorer pane and choose View Code from the shortcut menu.
At the top of the code window there are two drop-down lists, General and Declarations. Open the General list, scroll down and choose UserForm then open the Declarations list and choose Initialize.
You might notice that the Visual Basic Editor tries to anticipate your requirements and also enters the text:
Private Sub UserForm_Click() End Sub
Unfortunately this isn't what you need but you can safely ignore it or, if you prefer you can delete it (the Visual Basic Editor will delete it anyway later, if it remains unused, when you compile your code).
The Visual Basic Editor has written the first and last lines of the UserForm's Initialize event procedure:
Private Sub UserForm_Initialize() End Sub
Any code you type for this procedure should be entered between these two lines.
The Initialize event occurs when the form opens, so you can make use of it to set up the form ready for use, by setting any default values for textboxes or option groups, and filling the lists of any combo boxes.
It is usually a good idea to set a default value for an option group. It reminds the user that a choice has to be made. All you have to do it set the value of one of the option buttons to true with this line of code:
optGreeting1.Value = True
NOTE: It is good code-writing practice to press the Tab key before typing a line of code to indent the line from the margin (see the completed code procedure below). This makes code much easier to read later.
When filling the list of a combo box, each item should be added in the order that you want it to appear:
With cboInterviewLocation .AddItem "London" .AddItem "San Francisco" .AddItem "Lunar Station" .AddItem "Jupiter Station" .AddItem "Deep Space 7" .AddItem "Deep Space 9" End With
NOTE: This is called a "With statement". It saves you having to write "cboInterviewLocation" each time you add an item. "With statements" save time in code writing and help the code run more quickly.
To set an initial value for a textbox enter a line similar to this:
txtInterviewTime.Value = "10.00 am"
Here is the finished UserForm_Initialize procedure for the example form.
Private Sub UserForm_Initialize() optGreeting1.Value = True With cboInterviewLocation .AddItem "London" .AddItem "San Francisco" .AddItem "Lunar Station" .AddItem "Jupiter Station" .AddItem "Deep Space 7" .AddItem "Deep Space 9" End With With cboInterviewDay .AddItem "Monday" .AddItem "Tuesday" .AddItem "Wednesday" .AddItem "Thursday" .AddItem "Friday" End With With cboInterviewDuration .AddItem "½ hour" .AddItem "1 hour" .AddItem "2 hours" .AddItem "all morning" .AddItem "all afternoon" .AddItem "all day" End With With cboSenderAddress .AddItem "London" .AddItem "Jupiter Station" .AddItem "Deep Space 9" End With End Sub
Coding the 'Clear' Button
Clicking this button will restore the form to its original values. All the textboxes and combo boxes will be emptied (i.e. blank) and any option groups reset. Use the drop-down lists at the top of the code window to create a cmdClear_Click procedure.
NOTE: Another way to open an event procedure for a control is to double-click the control in the form design window.
Here's the procedure code for the example form:
Private Sub cmdClear_Click() optGreeting1.Value = True txtRecipientName.Value = Null txtRecipientAddress.Value = Null txtSalutation.Value = Null txtPosition.Value = Null cboInterviewLocation.Value = Null cboInterviewDay.Value = Null txtInterviewDate.Value = Null txtInterviewTime.Value = Null cboInterviewDuration.Value = Null txtSenderName.Value = Null txtSenderPosition.Value = Null cboSenderAddress.Value = Null End Sub
Coding the 'Cancel' Button
This button allows the user to quit without creating a letter. Clicking the Cancel button will close the UserForm and throw away the active document (the unfinished letter):
Private Sub cmdCancel_Click() Unload Me ActiveDocument.Close SaveChanges:=False End Sub
NOTE: The keyword "Me" is shorthand for referring to the current form from one of its own event procedures.
Coding the 'OK' Button
The OK button has to perform several tasks. Here are some examples…
It must interpret the choice the user made from an Option Group and convert it into a value suitable for entering at one of the document's bookmarks. It does this by first declaring a string (text) variable and using a series of "If statements" to place a suitable value into the variable depending upon which of the option buttons has a value of "true":
Dim strGreeting As String If optGreeting1 = True Then strGreeting = "Yours sincerely" If optGreeting2 = True Then strGreeting = "Yours faithfully" If optGreeting3 = True Then strGreeting = "Kind regards" If optGreeting4 = True Then strGreeting = "Live long and prosper"
Sometimes a simple value, such as one the choices offered by the cboSenderAddress combo box needs to be translated into something more elaborate, such as a multi-line address:
Dim strSenderAddress As String If cboSenderAddress.Value = "London" Then strSenderAddress = "Galactic Enterprises" _ & vbCrLf & "1001 Federation Plaza" _ & vbCrLf & "London" & vbCrLf & "Earth" End If
NOTE: This section of code uses the underscore character "_" to break lines of code to make them easier to read, and the VBA keyword "vbCrLf" which represents a line break in the resulting string.
Finally, the cmdOK_Click procedure must transfer the values held in the variables above, and those entered into the other textboxes and combo boxes, to the bookmarks in the letter document. Each value is assigned to a bookmark with a line something like this:
ActiveDocument.Bookmarks("Salutation").Range.Text = txtSalutation.Value
As there are a lot of these, a "With statement" can be used. The completed procedure is shown below. Note also the use of Application.ScreenUpdating to hide any on-screen changes until the process finishes. The procedure finishes by closing the form.
Follow this link to see the code for the cmdOK_Click procedure [new window].
Code to Display the UserForm
The form needs to be displayed automatically when the user opens a document based on the letter template.
Find the ThisDocument entry for your letter document in the Project Explorer pane of the Visual Basic Editor (if you can't see it, double-click the Microsoft Word Objects folder to display it) and double-click it to open its code window.
Use the drop-down lists at the top of the code window to create a Document_New procedure. This event occurs when a new document is created from a template.
Enter a line of code to open the form thus:
Private Sub Document_New() frmInterviewInvitation.Show End Sub
Check the Code
The Visual Basic Editor will have warned you about most kinds of typing errors, grammatical errors and omissions that you might have made when entering your code. As a final check, open the Visual Basic Editor's Debug menu and choose Compile Project. This should alert you of any other things you might have forgotten, such as undeclared variables. When you are satisfied that all is OK, save the document.
This tool could be further enhanced by adding a validation routine to check that all the required information had been supplied; code to protect the document against further modification; automatic printing of the completed document etc.
Save the Document as a Template
When you are satisfied with your document you must save it as a Word Template. When you subsequently use a template you use Word's File > New command to open a copy of the template file rather than the file itself. This means that the original template document remains unchanged and will always open looking the way you intended.
Open the File menu and choose Save As to open the Save As dialog. In the Save as type section choose Document Template then enter a suitable name for your template and click Save.
NOTE: When choosing a location for your template you should bear in mind that when the user chooses File > New there are taken to the default Templates folder. This is a good place to save templates, as they are easily accessible from here. You can store your templates in any location but you should remember that they should always be opened for use using the File > New command. Only use the File > Open command if you want to open the template file itself for editing. You can also open a template for use by locating its file with Windows Explorer and double-clicking the file's icon.
Remember to test your template thoroughly and correct any errors before unleashing it on any other users.
This project will make use of a custom-built dialog box to collect information from the user. Such a custom dialog box, called a UserForm, is created and powered by VBA. This second part of the tutorial deals with building a UserForm to collect all the necessary information needed to complete the document created in the first part of the tutorial.
The document, the UserForm and its accompanying VBA code are contained within the same file. The work of building and coding the UserForm is done using in Word's Visual Basic Editor.
The Visual Basic Editor
For this step you need your document open in Word although the job of building the UserForm will be done in the Visual Basic Editor. Open the Visual Basic Editor by going to Tools > Macro > Visual Basic Editor or use the keyboard shortcut Alt+F11. Unless you have previously made changes here, the Visual Basic Editor opens with an empty code window, with Project Explorer and Properties panes displayed on the left of the main window. If they are not displayed, you can switch on the Project Explorer and Properties panes from the View menu.
The Project Explorer pane is used to navigate through the various objects that you will be working with. It works a bit like Windows Explorer with items grouped into a hierarchy of folders. Here you can see a reference to the documents currently open: the Normal template (which opens and is hidden whenever Word opens) and the letter you are working on. In this example the letter has been given the file name InterviewLetter.doc. Any other open documents will be listed here too.
In the Project Explorer pane click on the name of your letter document to select it and go to Insert > UserForm. This opens a blank UserForm in the code window, and an entry for the UserForm in the Project Explorer pane, and displays the Toolbox...
You will use the blank UserForm to build a custom dialog box to help your user complete the letter automatically. The Toolbox contains all the objects you might need to put on your form. If it does not appear either click the Toolbox button on the Visual Basic Editor toolbar or go to View > Toolbox.
Name and Caption the UserForm
In the Project Explorer click UserForm1 to select it and then move to the Properties Window below. The Properties Window shows a list of the properties of the currently selected object, in this case the UserForm itself.
Change the Name property to something more meaningful (object names must not contain spaces and it is customary to prefix form names with the code frm). This example uses the name frmInterviewInvitation.
Change the Caption property to what you would like to see on the form's header bar (the coloured bar at the top of each dialog box and window). This is what the user will see on the dialog box so choose something suitable. This example uses the caption Invitation to Interview.
When you make these changes you will see corresponding changes to the form itself and to the entries in the Project Explorer pane...
NOTE: You can save your work at any time by going to File > Save or clicking the Save button in either the Visual Basic Editor window or in the Word document window. The UserForm is saved as part of your letter document so, whilst you are still developing your new template, remember to save your changes whenever you close the document.
The next step is to add objects, called Controls to the form. Controls can take the form of a TextBox (used to enter free text), a ComboBox (which offers the user a drop-down list of options, an Option Group (where the user can make a choice by clicking Radio Buttons), a Check Box (where the user places a tick to select an item) or a Command Button (that the user clicks to give an instruction).
There are several other controls in the Visual Basic Editor toolbox and more can be added (such as a Calendar) in the form of ActiveX Controls.
Adding a Text Box
If you require only text input from the user, a TextBox control will suffice. Click the TextBox tool on the toolbox then click somewhere on the UserForm. A selected textbox control appears on the UserForm. You can move the control by dragging one of its edges, or change its size by dragging one of the white rectangles around its border. Resize the textbox and drag it to a suitable position on the UserForm, leaving enough room for a label if you plan to add one.
The Visual Basic Editor automatically assigns a name to each control you create (e.g. TextBox1). You can make the job of code writing much easier by giving each control a meaningful name. It would be sensible to give the textbox the same name as the bookmark it is related to. It is also conventional, but not essential, to prefix the name with a code that indicates the type of control. In this example, the first textbox will supply text to the RecipientName bookmark so it has been given the name txtRecipientName.
With the textbox selected use the Properties pane to change its Name property to something more relevant.
Adding a Label
Most controls need a label. Click the Label tool on the toolbox and click on the UserForm to create a label. The label's name is not really important in this instance but its content is. You can add content to a label either by clicking inside the label and typing directly into it, or by changing the label's Caption property in the Properties pane.
NOTE: Avoid the temptation to double-click on an object on the UserForm. The Visual Basic Editor interprets this as an instruction to open a code event procedure for the object - handy when you are writing the form's code but you don't need it right now. If you do it accidentally just press Ctrl+Tab until you return to the form design window (or use the Window menu to find it), or double-click the form's name in the Project Explorer pane.
The label can be resized in the same way as the textbox and can contain large amounts of text if necessary. Text will wrap and flow within the label as its shape and size are changed. Make sure that your label is big enough to display all your text. A quick way to resize a label to fit its caption exactly is to double-click one of the resizing handles.
Move the label to its correct position and deselect it so you can see how it looks. You can check its final appearance by pressing F5 to preview the form.
Text Box Variations
By default a textbox permits only one line of text. This is fine for most cases (such as the Recipient Name) but sometimes you want the user to be able to enter several lines, as will be the case with the Recipient Address textbox. The control is drawn in the same way but this time set the MultiLine property to True. Normally you would also want to provide a scrollbar so set the ScrollBars property to 2-fmScrollBarsVertical.
When entering data into this type of textbox the user should press Ctrl+Enter or Shift+Enter to create a new line. Another option is to set the EnterKeyBehaviour property of the textbox to True. When you do this the user can create a new line in the textbox just by pressing the Enter key.
NOTE: You can offer users hints by making use of a control's ControlTipText property. Enter a short message that you would like to appear as a tool tip when the user pauses their mouse over the control...
Offer Choices with a Combo Box
A combo box provides a simple way to offer a familiar drop-down list of entries from which the user can make a choice. Draw a combo box in the same way as you would a textbox, using the ComboBox tool.
When using a combo box you can choose whether or not to allow the user to make any entry, using the control like a textbox, or to limit their entries to those on your list. If you want to limit the user to the list you must set the MatchRequired property of the combo box to True.
Use the Name property to give your combo box a meaningful name. It is customary to use the prefix cbo when naming combo boxes. This one is called cboInterviewLocation.
NOTE: Most controls have many different property options available. The most commonly used properties are set as defaults. To find out more about any property, click on the property in the Properties pane and press the F1 key.
The task of creating the list itself is performed by a code procedure when the form opens. That will be dealt with later.
Offer Choices with an Option Group
Combo boxes can offer a large list of choices, but when you want to offer the user just a few choices sometimes an option group is more appropriate. An Option Group is a collection of Option Buttons (sometimes called Radio Buttons) placed within a Frame (in fact option buttons on a VBA UserForm do not need to be placed within a frame to work as a group, but it helps the user to understand that they work together).
When building an option group you can choose whether to use Option Buttons, Checkboxes or Toggle Buttons all of which will work the same way. Most commonly option buttons are used. When working as a group the user may only select one option. If they select another the previous choice is deselected.
In this example an option group is used to offer the user a choice of greetings with which to end the letter.
First, draw a frame on the UserForm. Don't worry too much about its exact size and shape - you can adjust that later. Use its Caption property to add a label to the top of the frame.
Now use the OptionButton tool to draw the required number of option buttons inside the frame, filling the descriptive label of each one by entering text into the Caption property or by typing directly into the label.
Use the Name property to give each option button a meaningful name. In my example I have called them optGreeting1 to optGreeting4. If you have chosen to place your option buttons inside a frame they will automatically behave together as a group. If you prefer not to use a frame - or wish to have more than one group of buttons - make use of the GroupName property of each option button. Controls with the same GroupName will work together as a group even if they are not enclosed inside a frame.
Add the Command Buttons
Finally, the form needs some buttons to initiate the various tasks the form has to perform. First, an OK button that will result in the data being transferred to the standard letter; a Cancel button to close the form and throw away the letter if the user changes their mind; and (optionally) a Clear Form button to reset the form to its original values if the user wants to start again.
In VBA these are known as Command buttons. Like the other controls they can be drawn on the form using the toolbox Command Button tool.
Use the Properties pane to give the buttons meaningful names and captions. The convention is to prefix the name of a command button with cmd (e.g. cmdClear, cmdOK and cmdCancel).
Three additional properties are useful when creating command buttons:
The Accelerator property allows you to specify a letter that the user can type as an alternative to clicking the button. This letter should be one of those included in the button's caption. That letter then appears underlined on the caption. To assign an accelerator to a different sort of control, such as a combo box or text box, set the Accelerator property of its label.
The Default property, if set to True, causes that button to be 'clicked' if the user presses the Enter key on their keyboard. This property should only be set on one of the buttons, and would normally be applied to the OK button. Whilst generally useful, you might want to omit this feature if you think the user is likely to press Enter before they have completed the form as it might result in the form closing prematurely. The 'default' button also remains highlighted to indicate its purpose unless the user tabs to a different button.
The Cancel property, if set to True, has the effect of 'clicking' the button to which it is applied when the user presses the Escape (or Esc) key on their keyboard. This feature could usefully be applied to the Cancel button.
That completes the design of the form. Before proceeding any further check its appearance to the user by selecting the form and pressing the F5 key. You may want to alter the form's layout or size before adding the VBA code (although the form's design can be modified at any time).
NOTE: When arranging controls on a form, you can move several controls together, retaining their relative positions, by performing a multiple select. The easiest way to do this is to use the mouse to draw a selection rectangle enclosing the controls you want to select. When you release the mouse all the enclosed controls are selected and can be moved as one.
|> > >|
Set the Tab Order
A final but important step in setting up the form is to check the Tab Order. This is the order in which the various controls will be visited when a user moves around the form by pressing their Tab key. An illogical order can be extremely frustrating for the user. Go to View > Tab Order to display a dialog box listing all the controls on the form in their current order. Use the buttons to rearrange the order if necessary. You can ignore the Label controls because, although they are listed here, they will be ignored by the tab order.
The completed form is shown below:
The Next Step...
In the next step of the tutorial we write the VBA code that will power the form.
Most businesses use form letters or standard documents, in which a few details need to be changed each time the document is created. The best way to deal with this is to save the document as a template. You can add form fields for the variable content to make the job of completing the document easier. But for the greatest control and ease of use, you can't beat the versatility of a VBA UserForm. A VBA UserForm is a custom dialog box, to which you can add all the features you would normally see in a regular Windows dialog box like text boxes, combo boxes, option groups, check boxes and more.
This three part tutorial shows you how to build an automatic document template for Microsoft Word. The template uses VBA to display a dialog box into which the user enters the necessary information. At the click of a button the information is transferred to the document and it's ready to print.
The first part of the tutorial deals with preparing the standard document. In the second part we design and build a VBA UserForm, and in part three we write the VBA code that powers the form.
Preparing the Standard Document
Your project might be a standard document such as a lease or contract, or a form letter such as a job offer or interview invitation. In this tutorial I use the example of an interview invitation.
The first task is to decide which parts of the document change each time, and which remain the same. If the document is a letter, for example, write it as if you were addressing it directly to an individual but, instead of entering any personal information, insert a bookmark.
For example, instead of writing "Dear Mr Green" you should write "Dear " and then enter a bookmark to define the place where the salutation "Mr Green" will be inserted from the UserForm. Before inserting your bookmarks you might find it useful to go to Tools > Options > View and tick the Bookmarks option. This ensures that you can see the position of a bookmark after you have inserted it.
Insert the Bookmarks
To insert a bookmark place your cursor where you want your inserted text to appear and go to Insert > Bookmark. This displays the Bookmarks dialog box. Type a name for your bookmark and click Add. Each bookmark in a document must have a unique name, and it makes sense to keep the names relevant and concise.
If you have opted to view bookmarks, as suggested above, you will see a grey marker denoting the position of the bookmark. If not, the bookmark will be invisible. This feature can be switched on and off at any time and does not affect the performance of the bookmark. You may prefer to have the bookmarks visible whilst you are creating the template, but hide them when you are using the document.
You don't need to leave any additional space for the text that will be inserted into your bookmark as this will happen automatically. If your inserted text will appear in the middle of a sentence, then your bookmark should have a space (or other suitable punctuation) on either side. If it is at the end of a sentence it should be followed immediately by the full-stop (period).
As you add bookmarks to your document they are listed in the Bookmarks dialog. This dialog also gives you the facility to delete bookmarks from your document, or to quickly go to a bookmark's position...
Bookmarks can be inserted as you type or you may prefer to type a sample document first, and then edit it to remove personalized text replacing each piece with a bookmark.
When designing out your document remember that, whilst the bookmark marker occupies only a small space, your inserted text will probably require more. This might affect the document's layout so take this into consideration if the layout is particularly important. Here's how the sample document looks after all the bookmarks have been inserted...
Make Use of Word Fields
Several kinds of self-updating information can be added to your document with the aid of Word fields. You can see that the letter contains a date. Don't type a date! If you do that it will have to be changed each time you use the template. Instead insert the date as a Word field. Place your cursor where you want the date to appear and go to Insert > Date and Time and choose the format you want. Make sure that the Update Automatically option is ticked and click OK to place the field in your document. This field will then display the current date whenever the document is opened (i.e. each time you create a new document using your new template).
Save the Document
Now is a good time to save your document. You can save it as a regular Word document (*.doc) and save it as a template later when all the work is finished.
The Next Step...
In the next step of the tutorial we build the VBA UserForm that will collect information from the user for insertion into the document.
As your database grows it is increasingly likely that you will want to send mailings to selected people rather than to everyone on the list. Word provides a tool to help you specify which members of your mailing list are included in a mail merge… Query Options.
About Query Options
Query Options makes use of information contained in the database itself, combined with rules that you set up, to select particular records to include in the mail merge. This means that, in order to make use of Query Options, your criteria for including or excluding people from your mailing must depend upon something that is referred to in the data.
For example, you may wish to mail only to people in a certain town (using the Town field to get the information), or perhaps companies whose names fall in a certain part of the alphabet (using the Company field to get the information).
Preparing the Merge Document
Start by creating your mail merge document in the normal way. When you are ready to run the merge choose Query Options to open the Query Options dialog box.
You will find a button for Query Options in the mail merge helper window, and another in the merge window. They both do the same thing.
The Query Options dialog box is in two parts. One lets you specify how you want your records filtered, the other lets you specify how (if at all) you want your records sorted. You can use either or both.
Defining a Filter
We'll start with the Filter Records tab. This presents you with a grid into which the filter criteria can be entered.
Each row of the grid represents a single criterion or condition.
The grid section is divided into three columns, Field:, Comparison: and Compare to:.
Field: provides a drop-down list of all the fields in your database. You don't need to have used all these fields in the body of your letter - certain fields might exist solely for the purpose of selecting records. Choose the appropriate field from the list. In this example I am choosing to mail to clients in a particular town. That information is to be found in the Town field.
Comparison: provides another drop-down list with a number of expressions (known as "operators") which instruct word how to make its decision about each particular record. I want Word to match records to a particular town so I have chosen Equal to.
Compare to: is a text box in which you type what is essentially the answer to the question "Compare to what?" I have typed the name of my chosen town.
The Filter Records section is also divided into several rows. This allows you to add further criteria to your filter and create a multiple selection rule. Supposing I wanted to further confine my mailing to clients whose names begin with letters from the first half of the alphabet.
Note that And has been chosen to link the two criteria (as opposed to Or). This means that Word will only include those records that can specify both criteria. In other words, to be included in the mailing the company must have a London address and its company name must fall within the range A - M.
When creating multiple selection criteria it is important to make the correct decision about whether to choose And or Or to link them. If I wanted to mail to clients in either of two towns I must choose "Or". If I chose "And" Word would look for addresses that contained both towns - and wouldn't find any!
Things get a bit more complicated when you need to specify multiple criteria relating to different fields. The best way to check if you've got it right is to read it out loud and see if it makes sense!
Look at the example above. Suppose I wanted to further refine this filter to choose only those companies with names in the range A - M. You might think it sufficient to add a third row specifying "And… Company… Less than… N". Wrong!
What you would get would be "Town equal to London" or "Town equal to Manchester and Company less than N". The And on the third line would only link it to the line above.
The correct way to define the filter is shown below. It means "Town equal to London and Company less than N" or "Town equal to Manchester and Company less than N".
Your filter can contain up to six rows of instructions.
If you find it difficult to construct a suitable filter, you may find it useful to add one or more fields to your database that can be used to classify the various members of your mailing list. These fields would not necessarily be utilised in the merge document itself, but would be a great help when designing the filter.
Defining a Sort
Although you don't have to make use of the Sort Records option, it can be a very useful tool. Mailing lists tend to grow and change, and end up arranged in no particular order. The Sort Records option allows you to request that documents be printed in a particular order regardless of the arrangement of the original data.
If you don't ask for a particular sort order, the documents will be printed in the order that the records occur in the database.
You can choose to sort by up to three different fields, and each can be sorted in ascending (A - Z) or descending (Z - A) order. Simply choose the appropriate field(s) from the drop-down list.
Remember, if you want to print your whole mailing list in a particular order, you can use Sort Records without using Filter Records. When you have finished specifying the query options, click <OK> to return to the mail merge helper or the merge window. You are now ready to run the merge.
TIP: If you use mail merge to create letters, then again to print labels or envelopes for the same mailing, remember to use the same sort order for both! You don't want to waste time trying to match letters with envelopes!
Choosing How Many Records to Merge
The Merge window contains a further option to let you specify how many records are merged.
If you have a large mailing list and would rather perform the merge in stages, you can ask for a particular batch of records to be merged now and merge the rest at another time.
For example, if you have 200 names on your mailing list, you could ask for records 1 - 50 today, 51 - 100 tomorrow, 101 - 150 the next day and so on. This also avoids tying up the printer with one very long job.
About Ask Fields
An Ask field is a field you place in a mail merge document when you want to add some information that isn't contained in your data source. Ask fields are used in conjunction with Bookmarks.
You place the Ask field near the beginning of your merge document. When you perform the merge the Ask field prompts you to enter some text that it then inserts into each merged letter in the place (or places) where you have created Bookmarks.
Step 1: Inserting the Bookmarks
Place your cursor (point and click) in the space where you want to insert the information in the document. In my example (below) I am inserting some information in the middle of a sentence. You are going to create a kind of field called a bookmark. Word will use this bookmark as an indication of where it should insert the new information.
TIP: Remember to type two spaces when you leave a space for your bookmark. This ensures that your inserted text has a space both before and after it in the finished document
There are two stages to creating a bookmark. First press Ctrl+F9 to insert a pair of field characters (curly brackets) at the location of the cursor.
Now type a name for your bookmark so that it appears between the field characters. Use this method to create as many bookmarks as you need, giving each the same name.
TIP: Keep your bookmark names short and meaningful. This helps avoid errors and confusion if you have several different ones in a document. A bookmark name can be up to 40 characters long with letters, numbers, the underscore (_), but no spaces.
Step 2: Inserting the Ask Field
Now you are ready to insert the Ask Field. When Word encounters the Ask field during the merge it prompts the user for some information that is then inserted into the document at one or more points denoted by the bookmarks you have just created. The location of the Ask field itself is not important (you will not see it in the finished document) but it should be placed before the first of the bookmarks to which it refers.
The Ask field will be inserted wherever you cursor is located. In this example I placed my cursor in the empty line under the text "Dear Customer" near the beginning of my document.
From the Mail Merge toolbar choose Insert Word Field > Ask… to open the Insert Word Field: Ask Field dialog box.
TIP: You could have gone to the main menus and chosen Insert > Field and chosen Ask from the Mail Merge category. Doing it from the Mail Merge toolbar is easier because you get a dialog box to help you define the field.
The dialog box has four sections (Fig. 5)…
The Bookmark: box. Type the name of the bookmark(s) here.
The Prompt: box allows you to type a message that will appear when the merge runs. In my example I typed the words "Enter the date of the next open evening".
The Default Bookmark Text: box lets you specify some text that will be inserted automatically if the user doesn't type anything else. I have added the words "the last Friday of this month".
The Ask once check box gives you the choice of inserting the same text into all the documents at one go. The user is prompted for some text when the merge starts and that text is used for all the documents. That is what I want to do so I have ticked the box.
Point at the different sections of the illustration below to see a description of their function...
TIP: If you want to make a different entry for each merged document you will need to add an additional instruction to the Ask field. Refer to the tutorial on Fill-in fields to find out how to do this (see: Modify the Fill-in Field).
When you finish completing the dialog box click <OK>. Word displays a sample of the Ask prompt as it will appear when the merge is run.
This shows the Ask dialog box displaying the chosen default entry...
Step 3: Checking Your Work
Use Alt+F9 to display the document's field codes. This shows the instructions that Word uses during the merge. You can check for any mistakes you may have made in the previous step and edit them directly from here. Simply change the text within the code itself. This is also useful if you run the merge at another time and you want to have different text for the prompt or the default entry. It saves you having to create the field again from scratch. Here's what it looks like...
Use Alt+F9 again to hide the field codes. You don't have to do this but Word remembers the command from document to document. If you leave it switched on you may be confused tomorrow when you see field codes where you were expecting to see something like a date or a page number. You can also access this command from Tools > Options > View.
Step 4: Running the Merge
You are now ready to run the merge as normal. You can either return to the mail merge helper by choosing Tools > Mail Merge or you can click the appropriate button on the mail merge toolbar.
As the merge runs Word pauses when is comes to the Ask field and prompts you for some text. If you checked the Ask once option it will do this only once, and put the same text in all the merged documents.
When the dialog box appears type the desired entry (in this example the date of an event) into the text box and click <OK>.
This is how the Ask prompt appears during the merge...
TIP: Save time! Instead of using the mouse to click the <OK> button press Tab then Enter. Tab moves the focus to the <OK> button and Enter presses it.
If you chose the Ask once option the mail merge will continue without prompting you for additional information.
Your finished documents will now display a personalised entry in the appropriate place(s). Here's the completed merge...
Did you ever need to check a date before you typed it into a document? This tutorial shows you how to create a pop-up calendar using the Microsoft ActiveX Calendar Control that is installed with Office. You will be able to call up the calendar with a keyboard shortcut, from a toolbar button or menu, or from the right-click context menu. When you select a date it is automatically entered into your document at the insertion point...
The calendar will be build on a VBA UserForm and powered by VBA code. It will insert a date in a pre-defined format which you decide when you create the tool. If you want to add further refinements, such as allowing the user to choose the date format and set it as the default if they wish, you can continue with the second part of the tutorial: A Pop-up Calendar for Word Part 2: Customizing the Calendar.
Already Made a Pop-up Calendar for Excel?
If you have already made a calendar in Excel using my tutorial A Pop-up Calendar for Excel you will find that the UserForm used here is the same as the one in the Excel tutorial. However, the code behind the form is different so you might like to skip the first part of this tutorial and jump straight to the coding section.
Isn't There Already a Date Tool?
Microsoft Word is equipped with a tool for inserting the current date into a document. The command Insert > Date displays a dialog box inviting you to select a format:
Where Does the Code Go?
You can build the calendar in Normal.dot which is Word's "Normal" template. It is loaded whenever Word opens so if placed here, you calendar will always be available to you. If you plan to distribute the calendar tool to other users it would be better to create it in a new, empty document which can be saved as a template. This template can be loaded automatically like an Add-In, so that it is available whenever Word opens, without the need to alter individual users' copies of Normal.dot.
Building the Calendar
Step 1: Open a New UserForm
Open Microsoft Word. If you are planning to create your calendar in a template you will need a new, empty document. Next, open the Visual Basic Editor by choosing Tools > Macro > Visual Basic Editor (or keys: Alt+F11).
In the Project Explorer window, normally in the upper left corner of the Visual Basic editor) locate and click on the document in which you want to build the calendar, either Normal (the Normal Template) or Project (Document1) (where "Document1" is the name of your new, empty document in Word). If the Project Explorer is not visible, open it from the View menu.
In this example I am going to create the calendar in the new document (shown here as "Document1").
The Properties Window (usually located in the lower left corner of the Visual Basic Editor) displays all the properties of the the currently selected object. If the Properties Window is not visible open it from the View menu. Click on the UserForm to select it and make the following changes in the Properties Window:
Step 2: Locate the Calendar Control Tool
You need to draw a Calendar Control (active objects on forms are called "controls") on the UserForm, but the one you need is not normally included in the Toolbox. If you haven't already installed the Calendar Control tool, go to Tools > Additional Controls. If you find that the Additional Tools option is greyed-out, it's because the Toolbox is not visible. Switch it on with View > Toolbox. In the dialog box find Calendar Control 10.0 (10.0 for Word 2002, 9.0 for Word 2000 and 8.0 for Word 97) and select it. Click the <OK> button to close the dialog. This adds a new button to the toolbox, labelled Calendar:
NOTE: The Calendar Control is an ActiveX control (actually a file called mscal.ocx) supplied with Microsoft Office. It is normally installed with a standard installation of Microsoft Office Professional or Microsoft Access, but if you can't find it on the list you will need to get hold of a copy. If you are distributing your file, or planning to use it on more than one computer, you will also need to make sure that the host computer has the mscal.ocx file installed. You will find it on the CD that your copy of Microsoft Office Professional came on, or you can download a copy from here.
[Follow this link for full instructions on downloading and installing the mscal.ocx ActiveX Calendar Control file.]
Step 3: Add a Calendar Control to the UserForm
Click the Calendar tool then click on the UserForm near its upper left corner to place a calendar on the UserForm.
Make sure the calendar is selected then take a look at the choices in the properties window. Click on the Custom category (near the top of the list) and click the [...] button to open the calendar control's custom properties dialog. You can format the calendar any way you like. I made the following changes...
General - Show Month/Year Title: No
Omitting the title and making the text smaller allowed me to resize the calendar to a smaller rectangle by dragging the resize handles (white rectangles)...
Now click on the UserForm itself so that you can see its resizing handles and resize it to fit the calendar...
To get a preview of how the calendar will look click the F5 key. When you do this the UserForm will open in Word as it would in use. Click the UserForm's close button ([x]) to return to the Visual Basic Editor.
Step 4: Add a Command Button
If the user opens the calendar by mistake, they will be able to close it by clicking the [x] button without inserting a date on the document. Most users also expect a form or dialog box to close without making changes if they press the [ESCAPE] key on their keyboard. This doesn't happen by itself. You have to program the UserForm to respond to this event. To do this you will place a command button on the UserForm which closes it when clicked. By setting the button's Cancel property to True the effect of the user hitting the [ESCAPE] key will be to programmatically click the button. The user doesn't need to see the button, so you can hide it behind the calendar.
Click the Command Button tool on the toolbox then click on the calendar (just left of centre) to place a command button on the UserForm. Note that the command button places itself behind the calendar by default, although you can still see its outline when it is selected...
With the command button selected, make the following changes in the properties window... Name: cmdClose
Step 5: Write Code for the Command Button
This step adds some code to the Click event of the command button so that when clicked (i.e. when the user hits the [ESCAPE] key) the UserForm closes without anything else happening.
Go to View > Code (Keys: F7) to open the UserForm's code window. If the command button was still selected there will already be an entry. If not, choose cmdClose from the left hand (General) drop-down list at the top of the code window. It should automatically select Click from the right-hand (Declarations) list. Place your cursor between the Sub... and End Sub lines and press the [TAB] key to indent your code. Type Unload Me. Your line of code will look like this:
Use [CTRL]+[TAB] (or go to Window > frmCalendar(UserForm)) to switch back to the UserForm window and test the code. Press [F5] to open the form in Word. Notice that the command button is invisible (it is behind the calendar). Press the [ESCAPE] key and see that the UserForm closes.
Step 6: Write Code for the Calendar
This step builds the code that will transfer the date that the user chooses to the insertion point on the Word document. If anything is selected the selection will be replaced by the date.
Return to the UserForm's code window. Open the left-hand (General) drop-down list at the top of the code window and choose Calendar1. If it is not already selected, choose Click in the right-hand list. This enters the start and end lines of theCalendar1_Click procedure.
Place the cursor between the two lines and press [TAB] to indent your code (indenting blocks of code is good practice - it makes the code easier to read) then type:
Selection.Text = Format(Calendar1.Value, "dd mmmm yyyy")
...which transfers the date selected on the calendar to the insertion point on the document.
[NOTE: You can use any date format you choose. If you are unfamiliar with date format codes, see the explanation at the end of this tutorial.]
On the next line type:
Selection.MoveRight Unit:=wdCharacter, Count:=1
...which moves the insertion point to the end of the date text, ready for the user to continue typing. On the next line type:
...which closes the form. Your code should look like this:
To make the calendar a bit more user-friendly you will now add some code that checks to see if the user's selection already contains a date. If it does, then the calendar will show the same date when it opens. If there is no text selected (or if the selected text is not a date) the calendar will show today's date. To do this we make use of the UserForm's Initialize event, which happens as the UserForm opens.
Open the left-hand drop-down list at the top of the code window and choose UserForm, then open the right-hand list and choose Initialize. (You will notice that when you chose "Initialize" the start and end lines for the UserForm_Click procedure were created. You don't need these so it is safe to delete them.)
Place your cursor between the start and end lines of the UserForm_Initialize procedure and type the following:
If IsDate(Selection.Text) Then
This IF Statement checks the current selection for a date. If it is a date then the calendar displays the same date. If not it uses the VBA Date function to display the current date. Your completed code should look like this:
Now you need to write some code to display the UserForm on demand:
Type the line Sub OpenCalendar and press enter. The Visual Basic Editor places a pair of brackets at the end of the line and adds the line End Sub, placing your cursor between them. Press [TAB] then type frmCalendar.Show. Your code should look like this:
This simple procedure will display the UserForm when run from Word.
Step 7: Test the Code
At this point it is a good idea to save your file in case something goes wrong! In the Visual Basic Editor window select your file in the Project Explorer and choose File > Save Document1 (or whatever your file is called) and give it a suitable name. Save it as a document for now - you will convert it to a template later.
If you are working in Normal.dot select Normal in the Project Explorer and choose File > Save Normal.
Switch to Word and place the cursor where you want to insert a date. Choose Tools > Macro > Macros (Keys: Alt + F8) to open the Macro dialog. Make sure that the macro OpenCalendar is selected and click <Run>.
When the calendar opens it will display today's date. Choose a date (NOTE: always choose month and year before choosing day because clicking on a day fires the Calendar1_Click event). When you click the day the calendar closes and enters your date into the document.
Now type a date into your document, select it, and run the macro. If the program recognises that your selection is a date, the calendar will display that date when it opens. If you wish you can choose another date, or you can press the [ESCAPE] key to close the calendar without making any changes.
Step 8: Install the File
If you have been working in Normal.dot you don't need to do anything else, but remember to save the changes to the Normal Template if Word asks you when you close it down. If you intend to distribute your calendar, you will have followed my advice earlier to create it in a new document and later save it as a template. If you want to add the extra features of a keyboard shortcut and right-click menu option, continue with the tutorial. Otherwise jump to the final section "Install the Calendar" below...
Adding Extra Features
Adding a Toolbar Button or Menu Item
It is usually convenient to assign your macros to custom toolbar buttons or menu items. The method for doing this was covered in detail in my tutorial A Pop-up Calendar for Excel so I won't repeat it here. That tutorial also describes how to add a command to the context (right-click) menu and set a keyboard shortcut programmatically. The method for doing that in Word is slightly different from that in Excel so here's how to do it...
Assign a Keyboard Shortcut with Code
In the Visual Basic Editor double-click the ThisDocument entry in the Project Explorer for the document that contains your calendar. Open the left-hand (General) drop-down list at the top of the code window and choose Document and in the right-hand (Declarations) list choose Open. This creates the start and end lines for the Document_Open procedure. This is a special macro that runs automatically whenever the document is opened. Between the start and end lines type the lines:
CustomizationContext = NormalTemplate
NOTE: To make the code easy to read, some of the code lines have been broken using the VBA line-break character which is a Space followed by an Underscore ( _). This character ensures that the code is read as a single line. Without it the code would not be accepted.
These statements assign the keyboard shortcut Ctrl+Shift+C to the macro that opens the calendar UserForm. You can choose a different combination of keys if you wish. If your OpenCalendar procedure is in a different module you must enter the module name instead of "ThisDocument" or omit it (and the dot separator) altogether. Here's how the code should look:
This keyboard shortcut is assigned whenever the document is opened. It is a good idea to create a corresponding procedure to cancel the shortcut when the document closes.
In the same way as you did above, create a Document_Close procedure and enter the line:
On Error Resume Next
followed by the lines:
CustomizationContext = NormalTemplate
The first line tells Word to ignore any error that might occur in this procedure (this is safe to do here because the only possible error is that there is no such keyboard shortcut, so if the instruction to delete it fails it's OK to ignore it). Then comes the statement which cancels the keyboard shortcut assignment as the document closes. The code should look like this:
You will need to save and close the workbook and then reopen it before you can test your keyboard shortcut. If you are using Normal.dot you will need to close Word and reopen it. Save the file first!
Add an Item to the Right-Click (Context) Menu
It is also a simple matter to place a command on Word's text context menu. This will allow the user to right-click where the date is to be inserted and choose from the pop-up menu.
This is how you add an "Insert Date" entry (or whatever wording you choose) to the right-click menu. As with the procedure for assigning a keyboard shortcut, this requires two sets of code: one to create the menu item when the document opens, and another to remove it when the document closes.
First, find the Document_Open procedure in which you placed the code for creating a keyboard shortcut (or if you chose not to use a shortcut, create the procedure as described above). Insert the following line at the top of the procedure:
Dim NewControl As CommandBarControl
Move to the end of the procedure and add the line:
Set NewControl = Application.CommandBars("Text").Controls.Add
These two lines add the new control (i.e. menu item) to the menu (called in VBA a "command bar") that appears when the user right-clicks on text (i.e. on the editable part of a page). The next step is to describe the control's properties. Enter the following:
As before, if your OpenCalendar procedure is in a different module you must enter the module name instead of "ThisDocument" or omit it (and the dot separator) altogether.
The finished Document_Open procedure looks like this:
Finally, add this line to the end of the Document_Close procedure:
This line removes the entry from the right-click menu as the document closes. The finished Document_Close procedure looks like this:
Help! I've Got Too Many Menu Items...
Into the Immediate Window type the line:
then press the [Enter] key. Go back onto Word and right-click on the page. One of the "Insert Date" entries should have disappeared. Do it as many times as necessary to remove the unwanted copies. Then look through your code and try to find the error that is causing the problem.
Installing the Calendar
Unless you have been working in the Normal template, your calendar will now have to be saved as a Word template (*.dot) file. So, the next step is to save your working document as a template in Word's Startup folder. The reason for storing it here is that it will open automatically (and invisibly) whenever Word is started so the pop-up calendar tool will be available to any document.
First you need to ascertain the location of the Word's Startup folder on your computer. This differs with different versions of Windows and Office, and several programs have their own Startup folders, so it is important to get the right one. In Word choose Tools > Options > File Locations and locate "Startup" in the list:
To automatically install the Popup Calendar template for the first time you must close Word and open it again. After that it will load by itself each time Word opens.
Using the Pop-up Calendar
From now on each time you start Word the Pop-up Calendar will be available by using the keyboard shortcut you assigned or from the new item on the right-click menu.
If you chose not to add these enhancements you can open the calendar by running the OpenCalendar macro as described in Step 7: Test the Code above. You can also add a custom toolbar button or menu item if you wish.
Deactivating the Pop-up Calendar Template
You can temporarily deactivate the Pop-up Calendar template from Word by choosing Tools > Templates and Add-Ins where you will see it listed in the Templates and Add-Ins dialog. Remove the tick from the checkbox next to the template's name to unload the template for the current session. If you want to prevent the template from loading at startup you should also remove the template file from the Startup folder. [Click the thumbnail below to see a full-sized image of the Templates and Add-Ins dialog.]
Modifying the Pop-up Calendar Template
The Visual Basic Editor will not allow you to view the code of a template that is loaded from the Startup folder. If you attempt to do so a message will be displayed notifying you that the "Project is unviewable". If you need to modify the code, first deactivate the template as described above, then open the file in Word using the File > Open command. You will then be able to work on the code as normal.
Different Versions of Word
The VBA code used in this tutorial is suitable for all current versions of Microsoft Word (97, 2000 and 2002). If you create the Pop-up Calendar template in one version of Word and plan to use it in another version you should not encounter any problems but it is a good idea to check first. Each version of Microsoft Office comes with its own version of the ActiveX Calendar Control (8.0 for Office 97, 9.0 for Office 2000 and 10.0 for Office 2002). The first time you activate the template in a version of Office different from the one in which you created it, the program should automatically substitute the existing Calendar Control to the one current for that version. I found that when converting back from Word 2002 to Word 2000 this resulted in a change in the font size of the calendar buttons. This was easily fixed by redrawing the calendar in the current version.
Date Codes Explained
There is a standard notation for specifying date formats using a combination of codes for day, month and year (also hour, minute and second of you wish to specify time):
Using these codes, in conjunction with slashes, spaces or other punctuation characters you can construct any date format you choose, for example:
In different parts of the world there are different conventions for writing dates. In the US dates are normally written in the order Month, Day, Year but in Europe Day, Month, Year is used. If you are not sure where your users will be located you may not want to "hard code" a date format into your code as this might lead to misunderstandings. Instead you can display the date based on the computer's date settings in the Regional Settings section of the Windows Control Panel. In VBA you can still retain a degree of control by choosing one of the VBA date formats, for example:
NOTE: The user can modify these settings so they might appear different from those shown here. The ISO standard date format is yyyy-mm-dd (ISO 8601) e.g.: 2003-09-27.
Download the File
You can download a fully working example of the Pop-up Calendar as a Word template (.dot) file. There is one for each version of Microsoft Word although they should convert easily between versions. If the template fails to run correctly, it will be because your system does not contain a copy of the ActiveX Calendar Control. See the note above for how to obtain a copy. To download one of the files right-click the link and choose Save Target As...
Want to Build a Better Calendar?
Do you want to build a more fully-functioned calendar and learn some more useful VBA programming techniques? The second part of this tutorial shows you how to take the Pop-up Calendar project a step further by offering a the user a choice of formats and allowing a default date format to be set. Find out more in A Pop-up Calendar for Word Part 2: Customizing the Calendar.
Occasionally, when you're writing a document in Microsoft Word, you'll notice that you have an extra blank page at the end. To get rid of said page, move your cursor to the top of it and press the Backspace key.
In Microsoft Word, you can use a shortcut to select one sentence at a time. Press and hold down the Ctrl key and while continuing to hold down this key click with your left mouse button anywhere in the sentence you want to select or highlight.
Once a sentence has been selected let go of the Ctrl key, and you can press the Del key to delete that sentence or right-click and it to change its properties.
Bonus Tip: If you continue to hold down the Ctrl key after a sentence has been selected, and click and drag that sentence, you can make a copy of that sentence where you let go of the button.
Highlight any text in Microsoft Word and press the shortcut key Shift+F3 to change the case of the highlighted text. Pressing this key once will uppercase all highlighted text, pressing the shortcut again makes the text all lowercase, and then pressing the shortcut again gives the text proper case.
When copying text from another document or Internet web page and pasting it into Microsoft Word, Word will keep the formatting of the text. For example, if you were to copy the text on this page to a Word file, this text would remain bold, and this text would remain blue. To remove the formatting in Microsoft Word from any text highlight the text and press the shortcut key Ctrl+Spacebar. The shortcut sets the text to the default font, removes the formatting, and even removes links.
Alternatively, you can use the Paste Special option or Keep Text Only option in Microsoft Word to paste the text with no formatting.
Bonus Tip: In most versions of Windows Ctrl+Windows Key + V also pastes text as plain text.