简体   繁体   English

将UDF转换为数组UDF

[英]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! 我已经检查了如何制作单细胞阵列UDF,并且无法制作我所看到的东西,所以我想也许我最好问一下!

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. 我想知道是否有人可以帮助我弄清楚如何将UDF转换为可以处理范围的东西,然后可以平均其输出。

I have created a UDF to find the number of months in an age in this format: 我创建了一个UDF以这种格式查找年龄的月数:

Chronological Age

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

the UDF goes as follows: 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

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! 感谢您的时间!

You were kind of close, you just needed a For loop: 您有点接近,您只需要一个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

Works here- enjoy! 在这里工作-享受!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM