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 />

user what type of change to make to the cells. The solution is to present a dialog box like the one shown in<br />

Figure 41.1. This dialog box is a UserForm that was created by using the Visual Basic Editor, and it is displayed<br />

by a VBA macro.<br />

FIGURE 41.1<br />

A UserForm that asks the user for an option.<br />

Another solution is to develop three macros, one for each type of text case change. Combining these three<br />

operations into a single macro and using a UserForm is a more efficient approach, however. I discuss this<br />

example, including how to create the UserForm, in “Another UserForm Example,” later in the chapter.<br />

UserForm Alternatives<br />

Once you get the hang of it, developing UserForms isn’t difficult. But sometimes using the tools that are<br />

built into VBA is easier. For example, VBA includes two functions (InputBox and MsgBox) that enable<br />

you to display simple dialog boxes without having to create a UserForm in the VB Editor. You can customize<br />

these dialog boxes in some ways, but they certainly don’t offer the number of options that are available<br />

in a UserForm.<br />

The InputBox function<br />

The InputBox function is useful for obtaining a single input from the user. A simplified version of the<br />

function’s syntax follows:<br />

InputBox(prompt[,title][,default])<br />

The elements are defined as follows:<br />

n prompt: Text that is displayed in the input box. (Required)<br />

n title: Text that appears in the input box’s title bar. (Optional)<br />

n default: The default value. (Optional)<br />

The following is an example of how you can use the InputBox function:<br />

CName = InputBox(“Customer name?”,”Customer Data”)<br />

When this VBA statement is executed, Excel displays the dialog box shown in Figure 41.2. Notice that this<br />

example uses only the first two arguments for the InputBox function and does not supply a default value.<br />

When the user enters a value and clicks OK, the value is assigned to the variable CName. Your VBA code<br />

can then use that variable.<br />

716

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

Saved successfully!

Ooh no, something went wrong!