Excel VBA – 简单的平均计算

似乎很简单,但我没有得到预期的结果。

我的尝试,简化说明:

Sub myMacro2() Dim intLastRow As Long Dim intLastCol As Long Dim numAve As Double Dim i As Integer intLastRow = ActiveSheet.UsedRange.Rows.Count intLastCol = ActiveSheet.UsedRange.Columns.Count For i = 1 To intLastRow Step 1 numAve = Application.WorksheetFunction.Average(Cells(i, 2), Cells(i, intLastCol)) MsgBox "Row: " & i & " Ave: " & numAve Next i End Sub 

我这个例子的数据(5列,从左到右填充),空单元格视为NULL。

 A 111 B 111 C 111 222 333 444 D 111 222 E 111 222 333 F 111 222 

msgBox返回“111”作为每行的平均值。

我很确定我错过了一些基本的或显而易见的事情,但是它正在逃避我。

有什么build议吗?

您没有正确定义范围。

 Application.WorksheetFunction.Average(Cells(i, 2), Cells(i, intLastCol)) 

应该:

  Application.WorksheetFunction.Average(Range(Cells(i, 2), Cells(i, intLastCol))) ' ^^^^^^^ 

没有这一点,你只是平均两个单元格,而不是连接两个单元格的范围。