How to enter a formula into a cell using VBA?

若如初见. 提交于 2020-01-03 08:14:47

问题


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

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

But it enters into an excel worksheet with a mistake.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18807505/how-to-enter-a-formula-into-a-cell-using-vba

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