18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

VBA Examples 44<br />

Another way to approach this task is to define a custom function that returns True if the selection is a<br />

Range object, and False otherwise. The following function does just that:<br />

Function IsRange(sel) As Boolean<br />

IsRange = False<br />

If TypeName(sel) = “Range” Then IsRange = True<br />

End Function<br />

If you enter the IsRange function in your module, you can rewrite the CheckSelection procedure as<br />

follows:<br />

Sub CheckSelection()<br />

If IsRange(Selection) Then<br />

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

Else<br />

MsgBox “Select a range.”<br />

Exit Sub<br />

End If<br />

End Sub<br />

Identifying a multiple selection<br />

As you know, Excel enables you to make a multiple selection by pressing Ctrl while you select objects or<br />

ranges. This method can cause problems with some macros; for example, you can’t copy a multiple selection<br />

that consists of nonadjacent ranges. The following macro demonstrates how to determine whether the<br />

user has made a multiple selection:<br />

Sub MultipleSelection()<br />

If Selection.Areas.Count > 1 Then<br />

MsgBox “Multiple selections not allowed.”<br />

Exit Sub<br />

End If<br />

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

End Sub<br />

This example uses the Areas method, which returns a collection of all Range objects in the selection. The<br />

Count property returns the number of objects that are in the collection.<br />

The following is a VBA function that returns True if the selection is a multiple selection:<br />

Function IsMultiple(sel) As Boolean<br />

IsMultiple = Selection.Areas.Count > 1<br />

End Function<br />

Counting selected cells<br />

You can create a macro that works with the selected range of cells. Use the Count property of the Range<br />

object to determine how many cells are contained in a range selection (or any range, for that matter). For<br />

example, the following statement displays a message box that contains the number of cells in the current<br />

selection:<br />

MsgBox Selection.Count<br />

763

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

Saved successfully!

Ooh no, something went wrong!