Search code examples
arraysexcelvbaudf

Converting a UDF into an array UDF


I have checked on how to make single-cell array UDFs and cannot make head nor tail of what I have seen so I thought maybe I had better ask!

I was wondering if anyone could please help me figure out how to convert my UDF to something that can handle a range, the output of which could then be averaged.

I have created a UDF to find the number of months in an age in this format:

Chronological Age

    8:1
    8:2
    8:9
    8:1
    8:0
    7:10
    8:9

the UDF goes as follows:

Function GDAgeToMonths(YearsMonths As String) As Integer

Dim Colonz As Integer, Yearz As Integer, Monthz As Integer, Greaterz As Integer

' check if the stings consists of ">" sign
If InStr(YearsMonths, ">") >= 1 Then
    Greaterz = 2
Else
    Greaterz = 1
End If

' check position of ":" or "." sign
If InStr(YearsMonths, ":") >= 1 Then
    Colonz = InStr(YearsMonths, ":")
Else
    Colonz = InStr(YearsMonths, ".")
End If

Yearz = Mid(YearsMonths, Greaterz, Colonz - Greaterz)
Monthz = Right(YearsMonths, Len(YearsMonths) - Colonz)
GDAgeToMonths = Yearz * 12 + Monthz

End Function

So I was thinking something along the lines of:

Function GDAverageAge(AgeRange As Range) As Integer

Dim MonthsRange As Range, AverageMonths As Double

MonthsRange = GDAgeToMonths(AgeRange)

AverageMonths = WorksheetFunction.Average(MonthsRange)

GDAverageRange = GDMonthsToAge(AverageMonths)

End Function

With the function below to turn the average from months back to an age:

Function GDMonthsToAge(NumberofMonths As Integer) As String

Dim Yearz As Integer, Monthz As Integer
Yearz = NumberofMonths \ 12
Monthz = NumberofMonths - (12 * Yearz)
GDMonthsToAge = Yearz & ":" & Monthz
End Function

I really hope this makes sense!

I do not really know if it has to be an array formula per se or whether it would do something with a range but I am basically planning to use a formula to average the result of a formula run on each cell in a range.

Any help will be gratefully received!

Thank you for your time!


Solution

  • You were kind of close, you just needed a For loop:

    Function GDAverageAge(Ages As Range) As String
    Dim c As Integer, a As Integer, am As Integer, v As Variant
    'Counter of number of entries in range
    c = 0
    'Total value of range in months
    a = 0
    For Each v In Ages
    a = a + GDAgeToMonths(v.Value)
    c = c + 1
    Next v
    am = a / c
    GDAverageAge = GDMonthsToAge(am)
    End Function
    

    Works here- enjoy!