[英]Iterate over collection
I'm attempting to create a custom function to calculate a "mean monthly performance" percentage based on a cell range in Excel. 我正在尝试创建一个自定义函数,以根据Excel中的单元格范围计算“平均每月效果”百分比。 The function needs to ignore cells with a
0
value and the string "NA"
. 该函数需要忽略值为
0
和字符串"NA"
。
I'm not facing any problems building the collection from the cell range: 我在从单元格范围构建集合时没有遇到任何问题:
Function KROWPERFMEAN(rng As Range)
Dim val As Integer
Dim i As Integer
Dim cell As Range
Dim coll As Collection
Set coll = New Collection
i = 1
For Each cell In rng
If (cell.Value <> "NA" And cell.Value <> 0) Then
coll.Add cell.Value
End If
Next cell
When I try to loop through the collection, my code is breaking, not throwing an error and not returning a result: 当我尝试遍历集合时,我的代码中断了,没有抛出错误并且没有返回结果:
Dim perf As Variant
Dim y As Variant
'loop through collection and get perf
For Each y In coll
perf = perf + (coll(i) - coll(i + 1)) / coll(i)
'MsgBox (perf) '<-- both of these message boxes fire with exected #s
'MsgBox (i)
i = i + 1
Next
MsgBox ("This message box never fires with no errors thrown")
'assigned "1" to test, code is never reached
KROWPERFMEAN = 1
End Function
Is there an issue with how I'm looping over the collection? 我如何遍历集合是否存在问题?
I've tried several solutions (changing the y
type, declaring the variable in the For Each block) without success. 我尝试了几种解决方案(更改
y
类型,在For Each块中声明变量),但均未成功。
The problem is here: 问题在这里:
perf = perf + (coll(i) - coll(i + 1)) / coll(i)
With coll(i + 1), once you get to the end of the collection, then you are trying to access a member that does not exist. 使用coll(i + 1),一旦您到达集合的末尾,便会尝试访问不存在的成员。 The error it is silently failing with is "Subscript out of range".
静默失败的错误是“下标超出范围”。
Not knowing the details about your calculation, my best guess is you should probably do something like this because there is no second value to use to calculate on the last step. 不知道有关计算的详细信息,我最好的猜测是您可能应该执行类似的操作,因为在最后一步中没有第二个值可用于计算。
Function KROWPERFMEAN(rng As Range)
Dim val As Integer
Dim i As Integer
Dim cell As Range
Dim coll As Collection
Set coll = New Collection
i = 1
For Each cell In rng
If (cell.Value <> "NA" And cell.Value <> 0) Then
coll.Add cell.Value
End If
Next cell
Dim perf As Variant
Dim y As Variant
'loop through collection and get perf
For Each y In coll
If (i + 1 < coll.Count) Then
perf = perf + (coll(i) - coll(i + 1)) / coll(i)
End If
i = i + 1
Next
KROWPERFMEAN = perf
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.