2016-04-26 106 views
0

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

简单例子在这里:

+0

不宜行5之间的距离3是2而不是3? –

+0

@VincentG它应该是3先生,因为我想从自己的价值开始计算。如果第一个值在B1上,而下一个在B2上,那么结果值应该是2,因为我们从一行中的第一个值开始计数。 – vxpoisongas

回答

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