如何循环列并计算平均值?

时间:2017-03-29 07:26:30

标签: arrays excel vba excel-vba loops

Data series data series

我想找到一列中十个值的每个段的平均值。 (见数据系列图片) 不断一直到数据集的底部。数据集的长度可能不同,代码必须是“通用的”类型。

基于其他代码段,我试图这样做:

Sub tenthavg()

Dim currentIndex As Long
Dim myArray() As Variant
Dim rng As Range

ReDim myArray(1 To 10)     

Range("b1", Range("b1").End(xlDown)).Select
Set myArray = Selection        
currentIndex = 1

Do Until currentIndex + 1 > UBound(myArray)
    ActiveSheet.Cells(currentIndex, "T") = AverageOfSubArray(myArray, currentIndex, 10)
    currentIndex = currentIndex + 1
Loop                   

End Sub

'=================================================================

Function AverageOfSubArray(myArray As Variant, startIndex As Long,   elementCount As Long) As Double
Dim runningTotal As Double
Dim i As Long

For i = startIndex To (startIndex + elementCount - 1)
    runningTotal = runningTotal + val(myArray(i))
Next i
AverageOfSubArray = runningTotal / elementCount
End Function

不幸的是我无法让它发挥作用。我是以正确的方式接近这个吗?

如果是这样,我做错了什么?

2 个答案:

答案 0 :(得分:3)

恕我直言,这不是一个成功的方法......而不是Select EndDown和从交互式工作借来的其他概念利用了VBA自己的机制。

“通用”approch采用范围起始地址,批量大小和偏移量将结果作为参数放在哪里...

Sub AvgX(MyR As Range, S As Integer, ORow As Integer, OCol As Integer)
' MyR = start of range
' S   = batch size
' OCol, ORow = Offsets to place result in relation to last batch value
Dim Idx As Integer, Jdx As Integer, RSum As Variant

    Idx = 1
    RSum = 0
    Do
        For Jdx = 1 To S
            RSum = RSum + MyR(Idx, 1)
            Idx = Idx + 1
            If MyR(Idx, 1) = "" Then Exit Do
        Next Jdx
        MyR(Idx - 1, 1).Offset(ORow, OCol) = RSum / (Jdx - 1)
        RSum = 0
    Loop
End Sub

并由

调用
Sub Test()
    AvgX [C4], 10, 0, 1
End Sub

给你这个结果......

enter image description here

答案 1 :(得分:0)

您可以通过更简单的方式获得结果:

Sub tenthavg()

Dim LastRow As Long
LastRow = ThisWorkbook.Sheets("Your Sheet Name").Columns(2).Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
Dim myArray(1 To 10) As Double

If LastRow < 10 Then
    MsgBox "There's not enough data!"
Else
    On Error Resume Next
    For x = 1 To LastRow - 9
        For y = 1 To 10
            myArray(y) = ThisWorkbook.Sheets("Your Sheet Name").Cells(y + x - 1, 2).Value
        Next y
        ThisWorkbook.Sheets("Your Sheet Name").Cells(x, 20).FormulaR1C1 = 0
        ThisWorkbook.Sheets("Your Sheet Name").Cells(x, 20).FormulaR1C1 = Application.Average(myArray)
    Next x
End If

End Sub

请注意:我假设您的数据从B1开始,您希望列T上的输出。