2016-04-26 30 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