Home » excel » excel – Use of Average gives Application-defined or object defined error in VBA

excel – Use of Average gives Application-defined or object defined error in VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to find the average of the few cells using VBA, but when I run it, it gives me error.

This is the code I have written:

Sheets("1.A").Cells(124, 12) = Application.WorksheetFunction.Average("F" & matchStartRow & ":F" & matchEndRow)

Tried this as well:

Sheets("1.A").Cells(124, 12) = Application.WorksheetFunction.Average(Sheets("1.A").Cells("F" & matchStartRow & ":F" & matchEndRow))

I want to find the average of cells Fstart to Fend, but when I run the code, it gives application-defined or object defined error.

Not sure why there is such error. Need some guidance.

Full code:

Dim totalRowsinSheetA As Integer
totalRowsinSheetA = Sheets("1.A").Cells(Rows.Count, 1).End(xlUp).row
Sheets("1.A").Rows.Hidden = False
Sheets("1.A").Rows("3:" & matchStartRow - 1).Hidden = True
Sheets("1.A").Rows(matchEndRow + 1 & ":" & totalRowsinSheetA).Hidden = True


Sheets("1.A").Rows.Hidden = False

'Calculation of mean,VAR and cov
Sheets("1.A").Cells(124, 12) = Application.WorksheetFunction.Average("F" & matchStartRow & ":F" & matchEndRow)
How to&Answers:

You’re mixing your metaphors, or something :). You can either include VBA Range syntax in the Average WorksheetFunction:

Sub test()
Dim matchStartRow As Long
Dim matchEndRow As Long

matchStartRow = 2
matchEndRow = 5
Sheets("1.A").Cells(124, 12) = Application.WorksheetFunction.Average(Sheets("1.A").Range("F" & matchStartRow & ":F" & matchEndRow))
End Sub

Or you can use Application.Evaluate and construct a formula as it would appear in Excel:

Sub test2()
Dim matchStartRow As Long
Dim matchEndRow As Long

matchStartRow = 2
matchEndRow = 5
Sheets("1.A").Cells(124, 12) = Application.Evaluate("=Average(F" & matchStartRow & ":F" & matchEndRow & ")")
End Sub