vba 通过vba在Excel中添加单元格公式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2028160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:12:35  来源:igfitidea点击:

Add a cell formula in Excel via vba

excelvbaexcel-vbaformula

提问by e.James

I'm not an Excel or VBA expert but I want to insert this current excel formula into cell's using VBA.

我不是 Excel 或 VBA 专家,但我想使用 VBA 将此当前的 excel 公式插入到单元格中。

Current Excel formula:

当前 Excel 公式:

=IF(OR(ISNUM(D570)=FALSE;ISNUM(D573)=FALSE);"";IF(C573="Total";D573-D570;""))

VBA formula :

VBA 公式:

 ActiveSheet.Range("a" & ActiveSheet.Rows.Count).End(xlUp).Offset(2, 12).Value = "=IF(OR(ISNUM(R[-3]C[-9])=FALSE;ISNUM(R[0]C[-9])=FALSE);'';IF(R[0]C[-10]='Total';R[0]C[-9]-R[-3]C[-9];''))"

It doesn't work… Someone can help me please?

它不起作用......有人可以帮助我吗?

回答by e.James

Try using .formula =instead of .value =in your VBA code.

尝试在 VBA 代码中使用.formula =而不是.value =

Setting the .valueof a cell simply copies in whatever value you specify. In this case, your formula is simply converted to a string value.

设置.value单元格的 只是复制您指定的任何值。在这种情况下,您的公式只是转换为字符串值。

Using the .formulaproperty, you are actually specifying the formula that gets used to computethe value, which is what you are looking for.

使用该.formula属性,您实际上是在指定用于计算值的公式,这正是您要查找的内容。

回答by Gary McGill

Can I first suggest a simplification of your formula, from:

我可以首先建议简化您的公式,来自:

=IF(OR(ISNUM(D570)=FALSE;ISNUM(D573)=FALSE);"";IF(C573="Total";D573-D570;""))

...to...

...到...

=IF(AND(C573="Total"; ISNUM(D570); ISNUM(D573)); D573-D570; "")

Then, I'd set a cell (the active cell in the example below) to use that formula using the VBA code:

然后,我将使用 VBA 代码设置一个单元格(下面示例中的活动单元格)以使用该公式:

ActiveCell.Formula = "=IF(...)"