Type mismatch when setting a formula into a cell with VBA

℡╲_俬逩灬. 提交于 2020-07-09 14:48:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!