在VBA中查找列的平均值

时间:2015-09-30 21:43:42

标签: excel vba overflow average

我试图找到给定列中所有数字的平均值。

'Find the Average

Dim count As Integer
Dim sum As Integer
Dim lastCol As Integer
Dim c As Integer
Dim num As Long
lastCol = ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.count).Column
For c = 2 To lastCol
   sum = 0
   count = 0
ActiveSheet.Cells(2, c).Select
    Do While ActiveCell.Value <> ""
        sum = sum + ActiveCell.Value
        count = count + 1
        ActiveCell.Offset(1, 0).Activate
    Loop
    'num = sum / count
    ActiveCell.Value = sum / count
    'ActiveCell.Value = num

当我尝试运行它时,我收到行

的溢出错误
 ActiveCell.Value = sum / count

我尝试了很多不同的方法来解决这个问题。我试过的一个解决方案是使用一个中间长变量&#34; num&#34;在这种情况下传递值。上面已经说明了解决方案的尝试。我尝试的另一个解决方案是使用CLng()将变量强制转换为long。这两种解决方案仍然产生相同的溢出错误。有没有人知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

Here is an alternate way to get the average of all the cells in the last column of a worksheet, excluding the first row:

Sub Luxation()
   Dim lastCol As Long, rng As Range
   lastCol = ActiveSheet.UsedRange.Columns(ActiveSheet.UsedRange.Columns.Count).Column
   Set rng = Range(Cells(2, lastCol), Cells(Rows.Count, lastCol))
   MsgBox Application.WorksheetFunction.Average(rng)
End Sub