vba 如何使用VBA在单元格中输入公式?

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

How to enter a formula into a cell using VBA?

excelvbaexcel-formula

提问by enderland

I am trying to enter a formula into a cell which contains variable called var1a? The code that I have is:

我正在尝试将公式输入到包含名为 var1a 的变量的单元格中?我拥有的代码是:

    Worksheets("EmployeeCosts").Range("B" & var1a).Formula = ""SUM(H5:H""& var1a)

But it enters into an excel worksheet with a mistake.

但它进入了一个错误的excel工作表。

回答by enderland

You aren't building your formula right.

你没有正确构建你的公式。

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

这与以下几行的作用相同:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

这就是你想要做的。

Also, you want to have the =at the beginning of the formala.

此外,您希望=在正式开始时使用 。

回答by ??c Thanh Nguy?n

I would do it like this:

我会这样做:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

如果你有一些更复杂的公式,它会很方便