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

ON the CD-ROM<br />

This macro is available on the companion CD-ROM. The file is named skip blanks while looping.xlsm.<br />

Prompting for a cell value<br />

As discussed in Chapter 41, you can take advantage of VBA’s InputBox function to ask the user to enter a<br />

value. Figure 44.2 shows an example.<br />

FIGURE 44.2<br />

Using VBA’s InputBox function to get a value from the user.<br />

You can assign this value to a variable and use it in your procedure. Often, however, you want to place the<br />

value into a cell. The following procedure demonstrates how to ask the user for a value and place it into cell<br />

A1 of the active worksheet, using only one statement:<br />

Sub GetValue()<br />

Range(“A1”).Value = InputBox(“Enter the value for cell A1”)<br />

End Sub<br />

Determining the type of selection<br />

If your macro is designed to work with a range selection, you need to determine that a range is actually<br />

selected. Otherwise, the macro most likely fails. The following procedure identifies the type of object that is<br />

currently selected:<br />

ON the CD-ROM<br />

Sub SelectionType()<br />

MsgBox TypeName(Selection)<br />

End Sub<br />

A workbook that contains this macro is available on the companion CD-ROM. The file is<br />

named selection type.xlsm.<br />

If a cell or a range is selected, the MsgBox displays Range. If your macro is designed to work only with<br />

ranges, you can use an If statement to ensure that a range is actually selected. The following is an example<br />

that displays a message and exits the procedure if the current selection is not a Range object:<br />

Sub CheckSelection()<br />

If TypeName(Selection) “Range” Then<br />

MsgBox “Select a range.”<br />

Exit Sub<br />

End If<br />

‘ ... [Other statements go here]<br />

End Sub<br />

762

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

Saved successfully!

Ooh no, something went wrong!