11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

668<br />

Part VI: Developing Custom Worksheet Functions<br />

Consider the following Function procedure. This function accepts a range argument and<br />

returns the number of formula cells in the range:<br />

Function FORMULACOUNT(rng)<br />

cnt = 0<br />

For Each cell In rng<br />

If cell.Has<strong>Formula</strong> Then cnt = cnt + 1<br />

Next cell<br />

FORMULACOUNT = cnt<br />

End Function<br />

In many cases, the preceding function works just fine. But what if the user enters a formula like<br />

this one?<br />

=FORMULACOUNT(A:C)<br />

The three-column argument consists of 3,145,728 cells. With an argument that consists of one or<br />

more entire columns, the function does not work well because it loops through every cell in the<br />

range, even those that are well beyond the area of the sheet that’s actually used. The following<br />

function is rewritten to make it more efficient:<br />

Function FORMULACOUNT(rng)<br />

cnt = 0<br />

Set WorkRange = Intersect(rng, rng.Parent.UsedRange)<br />

If WorkRange Is Nothing Then<br />

FORMULACOUNT = 0<br />

Exit Function<br />

End If<br />

For Each cell In WorkRange<br />

If cell.Has<strong>Formula</strong> Then cnt = cnt + 1<br />

Next cell<br />

FORMULACOUNT = cnt<br />

End Function<br />

This function creates a Range object variable named WorkRange that consists of the intersection<br />

of the range passed as an argument and the used range of the worksheet. In other words,<br />

WorkRange consists of a subset of the range argument that only includes cells in the used range<br />

of the worksheet. Note the If-Then construct that checks if the WorkRange is Nothing. That<br />

will be the case if the argument for the function is outside of the used range. In such a case, the<br />

function returns 0, and execution ends.

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

Saved successfully!

Ooh no, something went wrong!