将 UDF 转换为数组 UDF

Converting a UDF into an array UDF

我已经检查了如何制作单元胞数组 UDF,但无法制作我所看到的内容的头部和尾部,所以我想也许我最好问一下!

我想知道是否有人可以帮我弄清楚如何将我的 UDF 转换为可以处理范围的东西,然后可以对输出进行平均。

我创建了一个 UDF 来查找以下格式的年龄中的月数:

Chronological Age

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

UDF 如下:

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

所以我在想一些事情:

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

使用下面的函数将平均值从几个月恢复到一个年龄:

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

我真的希望这是有道理的!

我真的不知道它本身是否必须是数组公式,或者它是否会用范围做某事,但我基本上打算使用公式来计算公式结果的平均值 运行在范围内的每个单元格上。

如有任何帮助,我们将不胜感激!

感谢您的宝贵时间!

你有点接近了,你只需要一个 For 循环:

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

在这里工作 - 享受!