用于计算行之间的值的距离并计算其平均值的Excel-VBA代码

如何计算行间单元格中特定值的距离并计算其平均值? 我正在处理3000行或更多的值。 很难一个一个地计算,因为它不但变化而且不断增加新的价值。 这让我很头疼 我真的很感激,如果一些天才可以在Excel VBA中解决这个问题。 如果有人可以实现这个使用数组公式,没有辅助单元更好。

这里有个简短的例子:

因为我上次是“坏人”,这次我会提供一个可行的UDF:

Public Function AVROW(rng As Range, str As String) As Double Set rng = Intersect(rng.Parent.UsedRange, rng) If rng.Rows.Count < 2 Then Exit Function Dim aCount As Long, aRow As Long, xCount As Long, xSum As Long While Not IsNumeric(Application.Match(str, rng.Rows(aRow + 1), 0)) aRow = aRow + 1 If aRow >= rng.Rows.Count Then Exit Function Wend Do aRow = aRow + 1 aCount = aCount + 1 If IsNumeric(Application.Match(str, rng.Rows(aRow + 1), 0)) Then xCount = xCount + 1 xSum = xSum + aCount + 1 aCount = 0 End If Loop While aRow < rng.Rows.Count - 1 AVROW = xSum / xCount End Function 

如果你一步步运行代码,应该是自我解释的。
但是,如果您仍然有任何问题,只需要问:)

在这里输入图像说明

另一种实现方法如下

 Public Function getaverage(r As Range, a As String) As Double Dim avgg As Double Dim matchount As Long Dim newex As Long For Each cell In r If cell.Value = a Then matchount = matchount + 1 If matchount = 1 Then Start = cell.Row Else newex = cell.Row - (Start - 1) avgg = avgg + newex Start = cell.Row End If End If Next getaverage = avgg / (matchount - 1) End Function 

在这里输入图像说明