11.08.2013 Views

Excel's Formula - sisman

Excel's Formula - sisman

Excel's Formula - sisman

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 25: VBA Custom Function Examples 705<br />

Returning an array of nonduplicated random integers<br />

The RANDOMINTEGERS function returns an array of nonduplicated integers. This function is<br />

intended for use in a multicell array formula. Figure 25-8 shows a worksheet that uses the following<br />

formula in the range A3:D12:<br />

{=RANDOMINTEGERS()}<br />

Figure 25-8: An array formula generates nonduplicated consecutive integers, arranged randomly.<br />

This formula was entered into the entire range by using Ctrl+Shift+Enter. The formula returns an<br />

array of nonduplicated integers, arranged randomly. Because 40 cells contain the formula, the<br />

integers range from 1 to 40. The following is the code for RANDOMINTEGERS:<br />

Function RANDOMINTEGERS()<br />

Dim FuncRange As Range<br />

Dim V() As Integer, ValArray() As Integer<br />

Dim CellCount As Double<br />

Dim i As Integer, j As Integer<br />

Dim r As Integer, c As Integer<br />

Dim Temp1 As Variant, Temp2 As Variant<br />

Dim RCount As Integer, CCount As Integer<br />

Randomize<br />

‘ Create Range object<br />

Set FuncRange = Application.Caller<br />

‘ Return an error if FuncRange is too large<br />

CellCount = FuncRange.Count<br />

If CellCount > 1000 Then<br />

RANDOMINTEGERS = CVErr(xlErrNA)<br />

Exit Function

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

Saved successfully!

Ooh no, something went wrong!