Average in a For Next Loop Macro

dludwig

New Member
Joined
Mar 14, 2011
Messages
3
I am trying to calculate averages in multiple columns using a macro and a for next loop. The code runs, but after running it gives me the following error: "Run-time error '1004': Unable to get the average property of the Worksheet function class". I used search on this message board, but I couldn't find how to fix my problem.

And "yes" a worksheet function will do this, but "no" I'm not going to use a worksheet function. There are too many calculations and this is very repetitive, I need to use numbers pasted into cells.

The portion of code giving me problems is:
.
.
.
End If
Cells(22, i + 1).Value = WorksheetFunction.Average(Range(Cells(31, i + 1), Cells(40, i + 1)))
Cells(20, i + 1).Value = (Cells(30, i + 1) / Cells(22, i + 1)) ^ 2
Next i
.
.

I've tried "With"/"End With" to specify the sheet, but what I tried didn't work:
.
.
.
End If
With Worksheets("Data")
Cells(22, i + 1).Value = WorksheetFunction.average (.Range(.Range(Cells(31, i + 1)), .Range(Cells(40, i + 1))))
End With
Cells(20, i + 1).Value = (Cells(30, i + 1) / Cells(22, i + 1)) ^ 2
Next i
.
.
I usually just use the macro recorder with a few small changes on my part, but this has me stumped and any help woud be greatly appreciated. And if all else fails, for j = 1 to 10 divided by 10, but that kinda reminds of the Geico caveman commercials.

Thank u,
dludwig
 
Last edited:

Some videos you may like

Excel Facts

Can a formula spear through sheets?
Use =SUM(January:December!E7) to sum E7 on all of the sheets from January through December

VoG

Legend
Joined
Jun 19, 2002
Messages
63,650
Try like this

Code:
With Worksheets("Data")
    .Cells(22, i + 1).Value = WorksheetFunction.Average(.Range(.Cells(31, i + 1), .Cells(40, i + 1)))
End With
 

dludwig

New Member
Joined
Mar 14, 2011
Messages
3
Thank you VoG for taking a look at it. I copied/pasted your lines of code into my module, and rem'ed out my code.

It still results in the same error with your code, "Unable to get the average property of the Worksheet function class".

I forgot to mention in my first post, I'm using Excel 2007 for windows.

Any more help will be greatly appreciated.

dludwig
 

dludwig

New Member
Joined
Mar 14, 2011
Messages
3
VoG, thank you for the help again.

I made a silly error copying/pasting. Fixed the error, IT WORKS!

Thanks again,
dludwig
 

Watch MrExcel Video

Forum statistics

Threads
1,108,956
Messages
5,525,883
Members
409,669
Latest member
JDCupps

This Week's Hot Topics

Top