简体   繁体   中英

Excel VBA- Average all numeric cells in a worksheet

I'm trying to create a macro that iterates over all used cells in a worksheet and return the average. The eventual goal is to get the average value of the numbers in each worksheet, and produce a line graph with the averages.

I'm having difficulty understanding how to do this. My strategy right now (which is probably sub-optimal) involves a) finding the first row with numeric data; b) finding the first column with numeric data; c) finding the last row with numeric data; d) finding the last column with numeric data; d) creating a range over those cells; e) averaging the range

Here's my current code

Sub AverageAllNumbers()
     Dim fRow As Long
     Dim fColumn As Long
     Dim lRow As Long
     Dim lColumn As Long
     Dim dblAverage As Long
     Dim averageRange As Range

    fRow = Cells.Find(What:=Number, SearchOrder:=xlByRows, SearchDirection:=xlNext).Row
    fColumn = Cells.Find(What:=Number, SearchOrder:=xlByColumns, SearchDirection:=xlNext).Column
    lRow = Cells.Find(What:=Number, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    lColumn = Cells.Find(What:=Number, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

    averageRange = Range(Cells(fRow, fColumn), Cells(lRow, lColumn))

    dblAverage = Application.WorksheetFunction.Average(averageRange)
    MsgBox dblAverage

End Sub

Almost nothing works-- 'lColumn' produces 16384, and fRow and fColumn produces 1, which is not even a used cell in my spreadsheet.

What's going on?

Have you tried using the Worksheet.UsedRange Property?

Sub AverageAll()
    Dim average As Double
    Dim averageRange As Range

    ' Set averageRange to UsedRange; no need to find it ourselves.
    Set averageRange = ActiveSheet.UsedRange

    average = Application.WorksheetFunction.average(averageRange)
    MsgBox average
End Sub

It worked for me in a test case, albeit a trivial one.

Should be a one-liner:

Sub SheetAverage()
    MsgBox Application.WorksheetFunction.Average(ActiveSheet.UsedRange)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM