将UDF转换为数组UDF

时间:2016-09-24 22:40:24

标签: arrays excel vba 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

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

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

感谢您的任何帮助!

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

你很亲密,你只需要一个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

在这里工作 - 享受!