Word Hacks [Electronic resources]

Andrew Savikas

نسخه متنی -صفحه : 162/ 108
نمايش فراداده

Hack 75 Include an Interactive Calendar in Your Forms

This hack shows you how to implement an easy-to-use calendar for choosing dates from within a form or other document.

If you use Word's Forms feature, many of your forms probably include DATE fields. Word provides some dates for you, such as today's date and the date a document was created. However, if you want the form's user to fill in a date, you can prompt the user to select the date from an interactive calendar, such as the one shown in Figure 8-5.

Figure 8-5. An interactive calendar placed in a form

The calendar used in Figure 8-5 is an ActiveX control included with Office. With some simple steps in the Visual Basic Editor, along with a few lines of code, you can easily add this calendar to any form. With your form template open, select ToolsMacroVisual Basic Editor.

In the Project Explorer, select your template and choose InsertUserForm. Next, select ViewToolbox to make the Toolbox visible. Right-click the Toolbox and choose Additional Controls to display the dialog shown in Figure 8-6. Scroll down and check the "Calendar Control 11.0" box (the version number may be slightly different on your system).

Figure 8-6. Activating the Calendar control

Click the OK button to add the Calendar control to your Toolbox. Click it and draw a new calendar on your blank UserForm, as shown in Figure 8-7. In the Properties window, change the UserForm's caption to "Calendar."

Figure 8-7. Add the Calendar control to a UserForm in the Visual Basic Editor

Next, select ViewCode and insert the following code:

Private Sub UserForm_Activate( )
Me.Calendar1.Value = Date
End Sub
Private Sub Calendar1_Click( )
Selection.Text = Calendar1.Value
End Sub

Now, in a code module in your template (if none exists, select InsertModule), add the following code:

Sub ChooseDate( )
UserForm1.Show
End Sub

Then select FileClose and Return to Microsoft Word.

Right-click the DATE field within the form in which you want the calendar to appear and choose Properties to display the dialog shown in Figure 8-8. Select the ChooseDate macro to run when the field is entered.

Figure 8-8. Select the macro to display the Calendar control

After choosing the date, close the calendar by clicking the Close button on its titlebar.

8.7.1 Hacking the Hack

Though it's ideally suited for fill-in forms, you may find the Calendar control useful in other documents too. To insert the Calendar control into any document, use a MACROBUTTON field, as shown in Figure 8-9. These fields assume you're using the same ChooseDate macro described above for activating the Calendar control. The field code is shown in the first field, and the field result is shown in the second field.

Figure 8-9. The first field shows the field code; the second shows the field result