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

时间:2016-04-26 07:27:38

标签: excel vba excel-vba excel-formula

如何计算行之间单元格中特定值的距离并计算其平均值?我正在处理3000行或更多值。很难一一计算它,因为它不仅会改变,而且还会不断增加新值。这让我很头疼。如果一些Genius可以在Excel VBA中为我解决这个问题,我将非常感激。如果有人可以使用没有辅助单元格的数组公式来实现这一点,那就更好了。

这里有一个简短的例子:

2 个答案:

答案 0 :(得分:2)

因为我是"坏人"上次,我这次提供了一个可行的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

如果你一步一步地运行代码,它应该是自我解释的 但是,如果您仍有任何疑问,请询问:)

enter image description here

答案 1 :(得分:1)

实现此目的的另一种方法如下

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

enter image description here