18.11.2014 Views

Microsoft Office

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Part VI<br />

Programming Excel with VBA<br />

Displaying a UserForm<br />

You also need to write a procedure to display the UserForm. You use the Show method of the UserForm<br />

object. The following procedure displays the UserForm named UserForm1:<br />

Sub ShowDialog()<br />

UserForm1.Show<br />

End Sub<br />

This procedure should be stored in a regular VBA module (not the code module for the UserForm). If your<br />

VB project doesn’t have a normal VBA module, choose Insert ➪ Module to add one.<br />

When the ShowDialog procedure is executed, the UserForm is displayed. What happens next depends on<br />

the event-handler procedures that you create.<br />

A UserForm Example<br />

The preceding section is, admittedly, rudimentary. This section demonstrates how to develop a UserForm.<br />

This example is rather simple. The UserForm displays a message to the user — something that can be<br />

accomplished more easily by using the MsgBox function. However, a UserForm gives you a lot more flexibility<br />

in terms of formatting and layout of the message.<br />

ON the CD-ROM<br />

This workbook is available on the companion CD-ROM. The file is named show message.xlsm.<br />

Creating the UserForm<br />

If you’re following along on your computer, start with a new workbook. Then follow these steps:<br />

1. Choose Developer ➪ Visual Basic (or press Alt+F11) to activate the VB Editor window.<br />

2. In the VB Editor Project window, double-click your workbook’s name to activate it.<br />

3. Choose Insert ➪ UserForm. The VB Editor adds an empty form named UserForm1 and displays<br />

the Toolbox.<br />

4. Press F4 to display the Properties window and then change the following properties of the<br />

UserForm object:<br />

Property<br />

Name<br />

Caption<br />

Change To<br />

AboutBox<br />

About This Workbook<br />

5. Use the Toolbox to add a Label object to the UserForm.<br />

6. Select the Label object. In the Properties window, enter any text that you want for the<br />

label’s Caption.<br />

7. In the Properties window, click the Font property and adjust the font. You can change the<br />

typeface, size, and so on. The changes then appear in the form. Figure 41.8 shows an example of<br />

a formatted Label control.<br />

724

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!