使用VBA将公式设置为单元格时,类型不匹配 [英] Type mismatch when setting a formula into a cell with VBA
问题描述
Worksheets("sheet2").Range("C2").Formula = "=AVERAGEIFS(Sheet1!E:E,Sheet1!A:A," >= "&A2,Sheet1!A:A," < "&B2)"
我已经在Excel 2007中运行了上面的代码,并且得到了
I have run the above code in Excel 2007 and I'm getting a
运行时错误13类型不匹配
run time error 13 type mismatch
以上代码用于从工作表1进行平均运算,然后在工作表2中输入.我需要一些纠正错误的帮助.
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.
推荐答案
问题是您需要使用其他引号将引号转义.这意味着公式中的所有引号"
都变为""
.
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)
,然后将其放入双引号" your formula here "
之间的字符串中,然后需要对公式中的所有引号进行转义,然后将"
更改为""
,如下所示:
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)"
另一个选择是使用Chr(34)
而不是"
.
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.
这篇关于使用VBA将公式设置为单元格时,类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!