如何计算除前两行之外的每列的平均值

时间:2013-12-09 22:57:09

标签: vba excel-vba average excel

我尝试计算除前两行之外的所有其他列的平均值。 因为前两行中有字母,所以会导致错误。 我想我需要更改sh1.Columns(col)此部分以排除前两行。 请给我一些想法。

谢谢

Sub average()

Dim sh1 As Worksheet, sh2 As Worksheet

Set sh1 = Sheets("combined")
Set sh2 = Sheets("avg")

Dim col As Long, row As Long

sh2.Cells.ClearContents

col = 4

Dim size As Long

'size = sh1.Range("A" & Rows.Count).End(xlUp).row
'size = sh1.Range(

sh2.Cells(1, 1).Value = "Average return"


'its from "parameter" sheet
For i = 1 To (42 - 11 + 1)

    'error caused by first two rows which include letters
     sh2.Cells(i + 1, 1).Value = Application.average(Columns(col))

     col = col + 2

Next i

End Sub

1 个答案:

答案 0 :(得分:0)

Application.Average可以解决此问题。下面快速而肮脏的解决方案。

我的设置:

enter image description here

代码(非常脏,必要时修改):

Sub Ave()
    For i = 1 To 7 Step 2
    Columns(i).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Value = Application.Average(Columns(i))
    Next i
End Sub

结果:

enter image description here

如果有帮助,请告诉我们。

编辑:

根据您的规格尝试以下代码。

Sub Avg()

    Dim Sh1 As Worksheet, Sh2 As Worksheet
    Dim tRow As Long

    With ThisWorkbook
        Set Sh1 = .Sheets("combined")
        Set Sh2 = .Sheets("avg")
    End With

    With Sh2
        .Cells.ClearContents
        .Range("A1").Value = "Average return"
    End With

    tRow = 2

    For i = 4 To 66 Step 2
        Sh2.Range("A" & tRow).Value = Application.average(Sh1.Columns(i))
        tRow = tRow + 1
    Next i

End Sub

如果有帮助,请告诉我们。