'VBA formula vs. function: get max of for loop

I have a simple for loop (e.g. to cumulate numbers recursively) realised as a VBA function. Now I need e.g. the max of the resulting values. Of course I can use max formula over the cell range with the results. But I need to find the max directly without the extra step of writing the result into cells, like "max of result of VBA function" I know it would work if the VBA function would return an array, but it doesn't. How can I solve this problem?

Can I force the VBA function to return the complete result array instead of single results?

Here is the VBA function

Function testyF(xt As Range, xtc As Range, xr As Range)
        n = 0
        For i = xr(1) To Application.Max(xr)
            If xtc.row >= xt(i).row Then
            n1 = xt(i)
            n = n + n1
            End If
        Next i
        testyF = n
End Function

Here is an excel screenshot showing that the VBA function itself works

=testyF($B$2:$B$5;B2;$A$2:$A$5)

but it does not work to get the max of the function when I try to applicate it to B2:B5, (that would work without the for loop):

=MAX(testyF($B$2:$B$5;B2:B5;$A$2:$A$5))

(correct max is 36, not 11)

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source