通过Excel VBA计算一行中每6列的平均值

问题描述 投票:0回答:2

如何计算表格中每 6 列组成的范围的平均值?

在 Excel 中,此公式类似于“=AVG(I3, O3, U3...HE3)”

我尝试了宏记录器,但它是通过重复整个公式和每个单元格地址来硬编码平均值。但我的表格每天都会更新,我在表格末尾添加了 6 个新列,最后一列左边,最后一列是存储一行中每 6 列平均值的列。

Dim i As Integer
i = 8
For i = 8 To rng.Columns.Count Step 6
rng.Cells(3, rng.Columns.Count) = Application.WorksheetFunction.Average(rng.Cells(3,i))
Next i

rng - 是存储我的表的范围变量。

我设法循环遍历需要计算平均值的所有单元格,但我不明白如何将这些单元格的值获取到计算平均值的特定单元格。

excel vba excel-2007
2个回答
2
投票

您可以将这些值相加,然后除以 (columns-8)/6 的数量。

Dim i As Integer
Dim sum as long
i = 8
sum = 0
For i = 8 To rng.Columns.Count Step 6
    sum = sum + rng.Cells(3,i).value
Next i

rng.Cells(3, rng.Columns.Count).offset(0,1).value = sum/((rng.columns.count-8)/6) ' I assumed you want the value in rng.columns.count +1, since but change it if you want.

编辑,不能使用 rng.columns.count+1 我认为因为范围以计数结束。将其更改为偏移。

另请注意,我们在此代码中没有错误检查。
我建议在添加总和之前使用类似

If Isnumber(rng.Cells(3,i).value) then
的内容,因为字符串值会破坏代码


0
投票

我还找到了一种替代方法来执行此操作,它类似于@Andreas,但我建议使用循环计数器来获取不为空的迭代值的数量。 就我而言,我需要获取由 6 列分隔的单元格范围的平均值。我有一个包含很多列和行的大表,我需要每行的平均值,所以这里是 @Andreas 修改后的代码:

Sub countAVG()
 
Dim i As Integer               ' row
Dim j As Integer               ' column
Dim sum As Long                ' sum variable that stores sum of all iterated values
Dim numberOfValues As Long     ' variable that stores the number of iterated values (that are not empty)
Dim rng As Range
 
Set rng = Range("B2").CurrentRegion
sum = 0
numberOfValues = 0
i = 3                          ' start from 3rd row
j = 8                          ' and 8th column
For i = 3 To rng.Rows.Count Step 1
    For j = 8 To rng.Columns.Count - 1 Step 6   ' skip 6 columns from every cell
        If IsEmpty(rng.Cells(i, j)) Then        ' if cell is empty then we skip it
        numberOfValues = numberOfValues         ' by leaving our number of cells as it is
        sum = sum                                                                            ‘ same with sum
        Else:
        numberOfValues = numberOfValues + 1     ' otherwise add 1 to a current number of cells values
        sum = sum + rng.Cells(i, j).Value       ' sum not empty cell value with our previous sum
        End If
    Next j
    On Error Resume Next    ' turning off error notifications in case all values are empty (better to use IsEmpty())
    rng.Cells(i, rng.Columns.Count).Offset(0, 1).Value = sum / numberOfValues
    On Error GoTo 0         ' turning back error notifications
    sum = 0
    numberOfValues = 0
Next i
 
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.