在行中查找平均值

时间:2014-01-15 16:59:28

标签: excel row average

好的,所以我有一份报告,包含多个人和不同月份的结果。我试图一次看3个月的平均值,但每个月都有不同的开始月份。我该怎么做?

示例:

  • NameA:结果将是2月至4月,然后是5月至7月的平均值
  • NameB:结果将是1月至3月等
  • NameC:3月至5月的结果

我的图表很糟糕抱歉没有照片允许

|Name|Jan|Feb|March|April|May|
| A  |   | 2 |  9  |  6  | 1 |
| B  | 1 | 8 |  9  |  4  | 3 |
| C  |   |   |  1  |  9  | 3 |

1 个答案:

答案 0 :(得分:0)

这是一个有效的解决方案:

    Sub add_averages()
        Dim r As Long, c As Long, right_c As Long
        r = 2
        Do While Not IsEmpty(Range("a" & r))
            c = 2
            'find first non-empty cell in row
            Do While IsEmpty(Cells(r, c)) And c <= 6
                c = c + 1
            Loop
            If c <= 6 Then
                dest_c = 7
                right_c = c + 2
                If right_c > 6 Then right_c = 6
                Cells(r, dest_c).Value = average_cells(r, c, right_c)
                If right_c < 6 Then
                    dest_c = dest_c + 1
                    c = c + 3
                    right_c = c + 2
                    If right_c > 6 Then right_c = 6
                    Cells(r, dest_c).Value = average_cells(r, c, right_c)
                End If
            End If
            r = r + 1
        Loop
    End Sub

    Function average_cells(r As Long, left_c As Long, right_c As Long) As Single
        'handles up to three numbers
        If left_c = right_c Then
            average_cells = Cells(r, left_c).Value
        ElseIf left_c + 1 = right_c Then
            average_cells = (Cells(r, left_c).Value + Cells(r, right_c).Value) / 2
        Else
            average_cells = (Cells(r, left_c).Value + Cells(r, left_c + 1).Value + Cells(r, right_c).Value) / 3
        End If
    End Function

它假设您想将结果平均值放在G和H列中。将列作为数字,我不能按照我想要的方式使用现有的平均函数,所以我自己写了。

希望这会有所帮助〜