0

I have a Custom User Function (UDF) that returns an array. I use it in an Array Formula on a large range of cells.
The length of the returned array is dependent on the function parameters. This works great except one thing: When the length of the returned array is smaller than the range defined for the array-formula, the "out-of-range" entries are all set to #N/A.

Is there a way to either obtain the array-formula range inside the custom user function (so, if needed, I could prepare a larger array to return), or alternatively return some kind of an iterator (instead of the array) which is not limited in size and would return "" in case of out-of-range?

2
  • 1
    Use ReDim Preserve to build your array as you feed it values. For an example you could refer to my answer here: Erase empty cells in an array. Commented Apr 29, 2015 at 15:54
  • 2
    Could you show your code? Commented Apr 29, 2015 at 15:56

1 Answer 1

1

Here is a pretty dumb example......a UDF to return the first 7 primes in column form:

Public Function Primes()
'
'   Array UDF to return the first 7 primes
'
    Dim rN As Long, ary(1 To 7) As Long
    Dim tdim As Long, i As Long
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction

    rN = Application.Caller.Rows.Count
    tdim = wf.Max(rN, 7)
    ReDim bry(1 To tdim, 1 To 1)

    ary(1) = 1
    ary(2) = 3
    ary(3) = 5
    ary(4) = 7
    ary(5) = 11
    ary(6) = 13
    ary(7) = 17

    For i = 1 To 7
        bry(i, 1) = ary(i)
    Next i

    If tdim > 7 Then
        For i = 8 To tdim
            bry(i, 1) = ""
        Next i
    End If
    Primes = bry
End Function

The UDF detects how many cells it has to fill and if that value exceeds 7, the balance is filled with blanks.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. All I needed was Application.Caller.Rows.Count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.