问题
Worksheets("sheet2").Range("C2").Formula = "=AVERAGEIFS(Sheet1!E:E,Sheet1!A:A," >= "&A2,Sheet1!A:A," < "&B2)"
I have run the above code in Excel 2007 and I'm getting a
run time error 13 type mismatch
The above code is used to do average operation from sheet 1 and enter in sheet 2. I request some help in correcting the error.
回答1:
The issue is you need to escape the quotes with another quote. That means all quotes "
in the formula become ""
.
If the formula in that cell should be
=AVERAGEIFS(Sheet1!E:E,Sheet1!A:A,">=" & A2,Sheet1!A:A,"<" & B2)
and you put it into a string between double quotes " your formula here "
, then you need to escape all quotes within the formula and change a "
into a ""
like below:
Worksheets("sheet2").Range("C2").Formula = _
"=AVERAGEIFS(Sheet1!E:E,Sheet1!A:A,"">="" & A2,Sheet1!A:A,""<"" & B2)"
Another option would be using the Chr(34)
instead of a "
.
Worksheets("sheet2").Range("C2").Formula = _
"=AVERAGEIFS(Sheet1!E:E,Sheet1!A:A," & Chr(34) & ">=" & Chr(34) & " & A2,Sheet1!A:A," & Chr(34) & "<" & Chr(34) & " & B2)"
This is technically the same but not very human readable in this case.
来源:https://stackoverflow.com/questions/46088338/type-mismatch-when-setting-a-formula-into-a-cell-with-vba