1

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
0

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Should the last line be: Cells(j, 20).Value = Application.WorkSheetFunction.Average(myRange)
Yep, edited in the answer. Thanks for catching it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.