how to avoid averageifs #DIV/0! using VBA - vba

I have the below code:
Sheet1.Range("AB3").Value = Application.WorksheetFunction.AverageIfs( _
.Range("AB5:AB" & CStr(i)), _
.Range("AB5:AB" & CStr(i)), _
">=0", .Range("AB5:AB" & CStr(i)), "<>N/A")
To get the average of a range and exclude -ve values and N/A values, but there is a moment when all range is N/A, so I'm getting the following error:
unable to get the average property of the worksheetfunction class
To avoid that I tried this:
Sheet1.Range("AB3").Value = Application.WorksheetFunction.IfError( _
Application.WorksheetFunction.AverageIfs( _
.Range("AB5:AB" & CStr(i)), _
.Range("AB5:AB" & CStr(i)), ">=0", _
.Range("AB5:AB" & CStr(i)), "<>N/A"), "N/A")
But with no luck. Any help will be appreciated.
EDIT:
In excel it works ok, but not in vba (in the code behind)
Just doing a little test in excel it works fine:
=IFERROR(AVERAGEIFS(AF5:AF10,AF5:AF10,"<>n/a"),"N/A")
in the above formula if data in range "AF5:AF10" is all "n/a", the formula returns "N/A" which is correct.

I'd just apply the formula to the cell in code. Here's two ways, one that puts the formula in the activecell and then "pastes" over it as a value, one that evaluates the formula and then puts that value in the activecell:
Sub Test1()
Dim i As Long
i = 10
Sheet1.Range("AB3").Formula = "=IFERROR(AVERAGEIFS(AF5:AF" & CStr(i) & ",AF5:AF" & CStr(i) & ",""<>n/a""),""N/A"")"
Sheet1.Range("B3").Value = Sheet1.Range("AB3").Value
End Sub
Sub Test2()
Dim strFormula As String
Dim i As Long
i = 10
strFormula = "=IFERROR(AVERAGEIFS(AF5:AF" & CStr(i) & ",AF5:AF" & CStr(i) & ",""<>n/a""),""N/A"")"
Sheet1.Range("AB3").Value = Application.Evaluate(strFormula)
End Sub

I found another solution to my question:
to avoid the:
unable to get the average property of the worksheetfunction class
just remove WorksheetFunction from the formula.
That's it.

Related

VBA Run time error 1004: Unable to set the formulaarray property of the range class

VBA Run time error 1004: Unable to set the formulaarray property of the range class
I've followed Dick Kusleika's advice in this link, but can't get the following array formula to enter into excel via VBA. Can anyone see where I'm going wrong? Both halves of the formula are easily below 255 characters.
Public Sub Configuration()
Dim theFormulaPart1 As String
Dim theFormulaPart2 As String
theFormulaPart1 = "=IF(ISODD(B2),IFERROR(INDEX(Race1Grid,MATCH(C2&I2&""Q3""," & _
"QualRace1ID&QualDriver&QSession,0)),IFERROR(INDEX(Race1Grid" & _
",MATCH(C2&I2&""Q2"",QualRace1ID&QualDriver&QSession,0)),INDEX" & _
"(Race1Grid,MATCH(C2&I2,QualRace1ID&QualDriver,0))))," & _
"X_X_X())"
theFormulaPart2 = "IFERROR(INDEX(Race2Grid,MATCH(C2&I2&""Q3"",QualRace2ID&" & _
"QualDriver&QSession,0)),IFERROR(INDEX(Race2Grid,MATCH(C2&" & _
"I2&""Q2"",QualRace2ID&QualDriver&QSession,0)),INDEX(" & _
"Race2Grid,MATCH(C2&I2,QualRace2ID&QualDriver,0)))))"
With Worksheets("Races").Range("V2")
.FormulaArray = theFormulaPart1
.Replace "X_X_X())", theFormulaPart2
End With
End Sub
I have tried splitting the formula onto more lines to make it easier to read.
As I mentioned in the comments, it's just the length of the first part of the formula. I suggest you simplify further:
Public Sub Configuration()
Dim theFormulaPart1 As String
Dim theFormulaPart2 As String
Dim theFormulaPart3 As String
theFormulaPart1 = "=IF(ISODD(B2),X_X_X1(),X_X_X())"
theFormulaPart3 = "IFERROR(INDEX(Race1Grid,MATCH(C2&I2&""Q3""," & _
"QualRace1ID&QualDriver&QSession,0)),IFERROR(INDEX(Race1Grid" & _
",MATCH(C2&I2&""Q2"",QualRace1ID&QualDriver&QSession,0)),INDEX" & _
"(Race1Grid,MATCH(C2&I2,QualRace1ID&QualDriver,0)))),"
theFormulaPart2 = "IFERROR(INDEX(Race2Grid,MATCH(C2&I2&""Q3"",QualRace2ID&" & _
"QualDriver&QSession,0)),IFERROR(INDEX(Race2Grid,MATCH(C2&" & _
"I2&""Q2"",QualRace2ID&QualDriver&QSession,0)),INDEX(" & _
"Race2Grid,MATCH(C2&I2,QualRace2ID&QualDriver,0)))))"
With ActiveSheet.Range("V2")
.FormulaArray = theFormulaPart1
.Replace "X_X_X())", theFormulaPart2
.Replace "X_X_X1()", theFormulaPart3
End With
End Sub

SUMIFS function from other workbook - Error is Type Mismatch

I would like to do SUMIFS function in a range of active sheet from other workbook. Here is where I get my error of Macro:
ActiveSheet.Range(ActiveSheet.Cells(6, lastCol + 1),
ActiveSheet.Cells(lastRow, lastCol + 1)).Formula = Application.WorksheetFunction.SumIfs(" ' " & wbGSD.Name & "'!$F$10:$F$" & wbGSDlastRow & ",'" & wbGSD.Name & "'!$B$10:$B$" & wbGSDlastRow & ",B6,'" & wbGSD.Name & "'!$C$10:$C$" & wbGSDlastRow & ", Total")
The error I got is:
Type Mismatch
I tried Sumif function. It didn't work either.
You're passing SumIfs() one long string. It doesn't take one long string. It takes a number of parameters, the first two of which are Range objects, not strings. If you want to write your formula as one long string, then there's no need for WorksheetFunction.SumIfs(). Just assign the string formula to the range's Formula property:
Range("A1").Formula = "=SUMIFS('" & wbGSD.Name & "'!$F$10:$F$" & ...
If you really do want to use WorksheetFunction.SumIfs(), you'll need to use it properly by passing individual parameters of the right type:
Range("A1") = WorksheetFunction.SumIfs( _
Sheets(wbGSD.Name).Range("$F$10:$F$" & wbGSDlastRow), _
Sheets(wbGSD.Name).Range("$B$10:$B$" & wbGSDlastRow), _
....

Run-time error '1004' when applying formula to Range.FormulaR1C1 in VBA

I'm trying to apply a big nested formula to a range using the code below. Basically, if the value in cell A of the active row exists in the column A of another workbook and if the cell in column E of the active row is not empty, I want the active cell to display the cells to display the value of the equivalent cell in a separate workbook.
This needs to be applied to several worksheets so I'm using the variables lrow (which is an int with the last row of the active worksheet in workbook#1) and tlrow (which is an int equal to the last row of the active worksheet in workbook#2). When I step through the sub, these variables both return the numbers I would expect them to.
Likewise, this is inside of a for loop so I also use Worksheets(i).Name where I is an int.
When I run the code, I get the run-time error "'1004': Application-defined or object-defined error".
I'm assuming it's a syntax issue.
Code:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & _
"'!A15:D" & tlrow & ",3,FALSE)),""0"",VLOOKUP(RC1,'[temp.xlsx]" & _
Worksheets(i).Name & "'!A15:D" & tlrow & ",3,FALSE))))"
Try using this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IF(ISERROR(VLOOKUP(RC1," & _
Worksheets(i).Range("A1:D" & lrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)),""0"",VLOOKUP(RC1," & _
Worksheets(i)..Range("A1:D" & tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & _
",3,FALSE)))"
What version of Excel are you running? In more recent versions you can use the Iferror function in this formula to really chop down the size.
It would be something like this:
Range("B15:B" & lrow).FormulaR1C1 = _
"=IF(OR(RC1="""",RC5=""""),"""",IFERROR(VLOOKUP(RC1," & " & Worksheets(i).Range("A1:D" & _
tlrow).Address(ReferenceStyle:=xlR1C1, External:=True) & ",3,0),""0"")"
Thanks for your help. I was able to resolve the problem by defining my vlookup range in a Range variable and then inputting the variable name in L42's equation in place of
worksheets(i).Range("A1:D" & lrow)
Really apprecaite the responses! Thanks again.

Using COUNTIF in VBA with last row

I'm quite new to excel and have been trying to get this Countif formula to work for a while now. I want it to count from the 12th row in column AN p till the last used row. I am very close now but when I run the macro it gives me a REF error.
Sub Date1()
'
' Enter Date
'
Range("B15") = InputBox("Enter Date")
Dim LR As Long
LR = Sheets("Design Risk Scoring Sheet").Range("AN" & Rows.count).End(xlUp).Row
Range("B16").FormulaR1C1 = _
"=COUNTIF('Design Risk Scoring Sheet'!R[-4]C[38]:RC[38](" & LR & "), ""<"" & R[-1]C )"
End Sub
This is what i get in the formula cell when I run the macro
=COUNTIF('Design Risk Scoring Sheet'!AN12:AN16(163), "<" & B15 )
It should ideally be AN163 instead of 16. I have tried removing RC[38] and putting AN instead but i get AN(163) which gives a #NAME error and if i remove the brackets in (" & LR & ") then I get single quotation marks in the formula :
=COUNTIF('Design Risk Scoring Sheet'!AN12:'AN163', "<" & B15 )
I dont know how to fix this problem?
Alternate:
Sub Date1()
Dim sDate As String
sDate = InputBox("Enter Date", "Date Entry", Format(Now, "m/d/yyyy"))
If Len(sDate) = 0 Then Exit Sub 'Pressed cancel
If Not IsDate(sDate) Then
MsgBox "[" & sDate & "] is not a valid date.", , "Exiting Macro"
Exit Sub
End If
Range("B15").Value2 = DateValue(sDate)
Range("B16").Formula = "=COUNTIF(AN12:AN" & Cells(Rows.Count, "AN").End(xlUp).Row & ",""<""&B15)"
End Sub
Try This..
Range("B16").FormulaR1C1 = _
"=COUNTIF('Design Risk Scoring Sheet'!R[-4]C[38]:RC[38](" & LR & "), < & R[-1]C )"

SUM formula VBA

I am trying to calculate the sum of changing cell range in vba. Unfortunately the cell values are variables. I can't seem to get the following formula to work.
Private Sub calcOverheadRate(startCell As Integer, endCell As Integer)
Total = endCell + 1
Range("D" & Total).Formula = "=SUM("D" & startCell & ":" & "D" & endCell)"
End Sub
I get compile error: "Expected: end of statement
To solve this problem I changed the function to,
Private Sub calcOverheadRate(startCell As Integer, endCell As Integer)
Dim start As String
Dim endC As String
start = "D" & CStr(startCell)
endC = "D" & CStr(endCell)
Total = endCell + 1
Range("D" & Total).Formula = "=SUM(start:endC)"
End Sub
The function compiles fine, when I run it, the value in the cell is "#NAME" where it references SUM(start:endC) not SUM(D5:D23)....
Any thoughts on how to solve this would be appreciated.
The quotes are the issue:
Range("D" & Total).Formula = "=SUM(" & startCell & ":" & endCell & ")"
I have figured out the problem the & needs to be inside the quotation for string literals
Range("D" & Total).Formula = "=SUM(" & start & ":" & endC & ")"
How about you try using a table?
Here is a 1 min video on how to make a table in Excel:
http://www.screenr.com/VvZ8