Search code examples
vbaexcelaverage

Average in VBA in Excel


I am new to VBA in excel. I have a range of data with 11 000 numbers. I want to calculate the average of first 60, then next 60 until the end. I did some programming but it isn't working. Can someone please help me with it?

Sub Hourlyaverage()
    Dim i As Long, j As Long, k As Long, l  As Long, m As Long
    
    Sheets("DUT1_Test51_excel").Select
    
    i = 3
    j = 3
    k = 63
        
    Do While Cells(i, 12).Value <> ""
        
        l = Cells(i, 12).Value
        m = Cells(k, 12).Value
        
        Cells(j, 20).Value = [Average (l : m)]
        i = i + 60
        j = j + 1
        k = k + 60
    Loop
    
End Sub

Solution

  • Look closely at what you're trying to do in this code:

    l = Cells(i, 12).Value
    m = Cells(k, 12).Value
    
    Cells(j, 20).Value = [Average (l : m)]
    

    You're assigning a "long" value to each of l and m and then calling them in the average function as if they were references to a cell.

    I suggest that you add a range variable, assign the location of the data you want to average and use that as your function argument.

    Something like:

    Dim myRange as Range
    
    'Loop code here
    Set myRange = Range("L" & i & ":L" & k)
    Cells(j, 20).Value = Application.WorksheetFunction.Average(myRange)