【问题标题】:How to loop through columns and calculate averages?如何遍历列并计算平均值?
【发布时间】:2017-08-22 13:24:57
【问题描述】:

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

很遗憾,我无法让它工作。我以正确的方式接近这个吗?

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

【问题讨论】:

  • 我刚刚意识到您已经找到/接受了答案。所以,我没有必要更新我的答案。
  • 您的帖子内容丰富 - 一个很好的资源。不应该被删除
  • 我的想法很简单:你喜欢我的一篇帖子-->你投票(以表达你的感激之情)并且帖子会保留。没有投票告诉我我的帖子没有用,它被删除了。简单的。只是在极少数情况下,每当我想将它们作为个人笔记保留时,我仍然会留下我的帖子。所以,下次你喜欢这个网站上的帖子时,只要确保你给它投票,我很确定帖子不会被删除。

标签: arrays vba excel loops


【解决方案1】:

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

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 上输出。

【讨论】:

  • 虽然这可能工作得很好,但是对于 B 列中的每个单元格,您要访问工作表上的一个单元格三次。这可能会很快加起来,并且会大大减慢速度。
【解决方案2】:

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

“通用”方法将 Range 起始地址、批量大小和将结果放置在何处的偏移量作为参数...

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

给你这个结果...

【讨论】:

    猜你喜欢
    • 2021-07-19
    • 2019-03-27
    • 1970-01-01
    • 2018-10-15
    • 2015-11-01
    • 1970-01-01
    • 2011-03-08
    • 1970-01-01
    • 2020-11-17
    相关资源
    最近更新 更多