在 VBA 函数中运行 EXCEL 公式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41889402/
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-12 11:58:54  来源:igfitidea点击:

Run EXCEL formula in VBA function

excelvbaexcel-vbaexcel-formula

提问by mojo

I have a custom function in VBA which I call from cell and I have a formula like this

我在 VBA 中有一个从单元格调用的自定义函数,我有一个这样的公式

"=SUM(SUMIFS(CURR_COUNT;MDL;""MODEL"";CURR_MDLCD;{CODES};RG;""REGIONID""))/SUM(SUMIFS(CURR_COUNT;MDL;""MODEL"";RG;""REGIONID"";CURR_MDLCD;""<>     ""))"

My custom function take some cells values and insert them to formula which is just string. After that I need to calculate formula and return result to cell from which I call the function? Can I calculate this formula in the function and return result to a cell?

我的自定义函数采用一些单元格值并将它们插入到只是字符串的公式中。之后我需要计算公式并将结果返回到我调用函数的单元格?我可以在函数中计算这个公式并将结果返回到单元格吗?

回答by zaphodalive

Assuming your formula string would work if it was actually put into a cell, then it should work if you use Application.Evaluate- but you don't include the equals sign.

假设您的公式字符串在实际放入单元格时会起作用,那么如果您使用它应该会起作用Application.Evaluate- 但您不包括等号。

e.g. To calculate

例如计算

=SUM(A1:B1)

in VBA you would use

在 VBA 中你会使用

Application.Evaluate("SUM(A1:B1)")