Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Excel_2010_Bible.pdf
Скачиваний:
26
Добавлен:
13.03.2015
Размер:
11.18 Mб
Скачать

Creating UserForms

You can’t use Excel very long without being exposed to dialog boxes. Excel, like most Windows programs, uses dialog boxes to obtain information, clarify commands, and display messages. If you develop

VBA macros, you can create your own dialog boxes that work very much like those that are built in to Excel. These dialog boxes are known as UserForms.

Why Create UserForms?

Some macros that you create behave exactly the same every time that you execute them. For example, you may develop a macro that enters a list of your sales regions into a worksheet range. This macro always produces the same result and requires no additional user input. You may develop other macros, however, that perform differently under different circumstances or that offer options for the user. In such cases, the macro may benefit from a custom dialog box.

The following is an example of a simple macro that makes each cell in the selected range uppercase (but it skips cells that have a formula). The procedure uses VBA’s built-in StrConv function.

Sub ChangeCase()

For Each cell In Selection If Not cell.HasFormula Then

cell.Value = StrConv(cell.Value, vbUpperCase) End If

Next cell End Sub

CHAPTER

IN THIS CHAPTER

Why create UserForms

UserForm alternatives

Creating UserForms: An

overview

UserForm examples

More on creating UserForms

837

Part VI: Programming Excel with VBA

This macro is useful, but it can be improved. For example, the macro would be more helpful if it could also change the cells to lowercase or proper case (only the first letter of each word is uppercase). This modification is not difficult to make, but if you make this change to the macro, you need some method of asking the user what type of change to make to the cells. The solution is to present a dialog box like the one shown in Figure 41.1. This dialog box is a UserForm that was created by using the Visual Basic (VB) Editor, and it is displayed by a VBA macro.

FIGURE 41.1

A UserForm that asks the user to select an option.

Another solution is to develop three macros, one for each type of text case change. Combining these three operations into a single macro and using a UserForm is a more efficient approach, however. I discuss this example, including how to create the UserForm, in “Another UserForm Example,” later in the chapter.

UserForm Alternatives

After you get the hang of it, developing UserForms isn’t difficult. But sometimes using the tools that are built into VBA is easier. For example, VBA includes two functions (InputBox and MsgBox) that enable you to display simple dialog boxes without having to create a UserForm in the VB Editor. You can customize these dialog boxes in some ways, but they certainly don’t offer the number of options that are available in a UserForm.

The InputBox function

The InputBox function is useful for obtaining a single input from the user. A simplified version of the function’s syntax follows:

InputBox(prompt[,title][,default])

The elements are defined as follows:

prompt: (Required) Text that is displayed in the input box

title: (Optional) Text that appears in the input box’s title bar

default: (Optional) The default value

838

Chapter 41: Creating UserForms

The following is an example of how you can use the InputBox function:

CName = InputBox(“Customer name?”,”Customer Data”)

When this VBA statement is executed, Excel displays the dialog box shown in Figure 41.2. Notice that this example uses only the first two arguments for the InputBox function and does not supply a default value. When the user enters a value and clicks OK, the value is assigned to the variable CName. Your VBA code can then use that variable.

FIGURE 41.2

This dialog box is displayed by the VBA InputBox function.

The MsgBox function

The VBA MsgBox function is a handy way to display information and to solicit simple input from users. I use the VBA MsgBox function in many of this book’s examples to display a variable’s value. A simplified version of the MsgBox syntax is as follows:

MsgBox(prompt[,buttons][,title])

The elements are defined as follows:

prompt: (Required) Text that is displayed in the message box

buttons: (Optional) The code for the buttons that are to appear in the message box

title: (Optional) Text that appears in the message box’s title bar

You can use the MsgBox function by itself or assign its result to a variable. If you use it by itself, don’t include parentheses around the arguments. The following example displays a message and does not return a result:

Sub MsgBoxDemo()

MsgBox “Click OK to continue”

End Sub

Figure 41.3 shows how this message box appears.

839

Part VI: Programming Excel with VBA

FIGURE 41.3

A simple message box, displayed with the VBA MsgBox function.

To get a response from a message box, you can assign the result of the MsgBox function to a variable. The following code uses some built-in constants (described in Table 41.1) to make it easier to work with the values that are returned by MsgBox:

Sub GetAnswer()

Ans = MsgBox(“Continue?”, vbYesNo)

Select Case Ans

Case vbYes

...[code if Ans is Yes]...

Case vbNo

...[code if Ans is No]...

End Select

End Sub

When this procedure is executed, the Ans variable contains a value that corresponds to vbYes or vbNo. The Select Case statement determines the action to take based on the value of Ans.

You can easily customize your message boxes because of the flexibility of the buttons argument. Table 41.1 lists the built-in constants that you can use for the buttons argument. You can specify which buttons to display, whether an icon appears, and which button is the default.

TABLE 41.1

Constants Used in the MsgBox Function

Constant

Value

Description

 

 

 

vbOKOnly

0

Displays OK button.

 

 

 

vbOKCancel

1

Displays OK and Cancel buttons.

 

 

 

vbAbortRetryIgnore

2

Displays Abort, Retry, and Ignore buttons.

 

 

 

vbYesNoCancel

3

Displays Yes, No, and Cancel buttons.

 

 

 

vbYesNo

4

Displays Yes and No buttons.

 

 

 

840

 

 

Chapter 41: Creating UserForms

 

 

 

 

 

 

Constant

Value

Description

 

 

 

vbRetryCancel

5

Displays Retry and Cancel buttons.

 

 

 

vbCritical

16

Displays Critical Message icon.

 

 

 

vbQuestion

32

Displays Query icon (a question mark).

 

 

 

VBExclamation

48

Displays Warning Message icon.

 

 

 

vbInformation

64

Displays Information Message icon.

 

 

 

vbDefaultButton1

0

First button is default.

 

 

 

vbDefaultButton2

256

Second button is default.

 

 

 

vbDefaultButton3

512

Third button is default.

The following example uses a combination of constants to display a message box with a Yes button and a No button (vbYesNo), and a question mark icon (vbQuestion). The second button (the No button) is designated as the default button (vbDefaultButton2), which is the button that is executed if the user presses Enter. For simplicity, these constants are assigned to the Config variable, and Config is then used as the second argument in the MsgBox function.

Sub GetAnswer()

Config = vbYesNo + vbQuestion + vbDefaultButton2

Ans = MsgBox(“Process the monthly report?”, Config)

If Ans = vbYes Then RunReport

If Ans = vbNo Then Exit Sub

End Sub

Figure 41.4 shows how this message box appears when the GetAnswer Sub is executed. If the user clicks the Yes button the routine executes the procedure named RunReport (which is not shown). If the user clicks the No button (or presses Enter), the procedure is ended with no action. Because the title argument was omitted in the MsgBox function, Excel uses the default title (Microsoft Excel).

FIGURE 41.4

The second argument of the MsgBox function determines what appears in the message box.

841

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]